标签:_id sel avg rom where pre art 获取 and
有两张表,如下
t_person, 员工表,包含年龄,姓名,以及部门id
t_department,部门表,包含部门id,部门名称
题1:获取每个部门的平均年龄
SELECT d.id, d. NAME, p.avg_age FROM t_department d LEFT JOIN ( SELECT avg(age) avg_age, department_id FROM t_person GROUP BY department_id ) p ON p.department_id = d.id
题2:获取年龄最大的员工(可能不止一个)
select * from t_person where age = (select max(age) from t_person);
题3:获取每个部门年龄最大的员工
SELECT * FROM t_person p JOIN ( SELECT max(age) max_age, department_id FROM t_person GROUP BY department_id ) t ON p.department_id = t.department_id AND p.age = t.max_age;
题4:获取每个部门大于平均年龄的员工
SELECT * FROM t_person p JOIN ( SELECT avg(age) avg_age, department_id FROM t_person GROUP BY department_id ) t ON p.department_id = t.department_id AND p.age >= t.avg_age;
标签:_id sel avg rom where pre art 获取 and
原文地址:https://www.cnblogs.com/zhangxuezhi/p/11963800.html