项目员工
需求一:查询每一个项目中员工的平均工作年限,精确到小数点后两位。
展示效果:
project_id | average_years |
---|---|
1 | 2.00 |
2 | 2.50 |
Create table If Not Exists 44_Project (project_id int, employee_id int);
Create table If Not Exists 44_Employee (employee_id int, name varchar(10), experience_years int);
Truncate table 44_Project;
insert into 44_Project (project_id, employee_id) values (1, 1);
insert into 44_Project (project_id, employee_id) values (1, 2);
insert into 44_Project (project_id, employee_id) values (1, 3);
insert into 44_Project (project_id, employee_id) values (2, 1);
insert into 44_Project (project_id, employee_id) values (2, 4);
Truncate table 44_Employee;
insert into 44_Employee (employee_id, name, experience_years) values (1, 'Khaled', 3);
insert into 44_Employee (employee_id, name, experience_years) values (2, 'Ali', 2);
insert into 44_Employee (employee_id, name, experience_years) values (3, 'John', 1);
insert into 44_Employee (employee_id, name, experience_years) values (4, 'Doe', 2);
最终SQL:
select
project_id ,
round(avg(experience_years),2) as average_years
from
44_Project p
left join
44_Employee e
on
p.employee_id = e.employee_id
group by
project_id
order by
project_id;