[英]MySQL query to find the name and age of the youngest employee in each department
[英]Find the salary of the youngest and eldest employee in each department
有两张桌子
1) Employee
id | Name | Department | Dob
2) Salary
id | salary
我想找到每个部门中最年轻和最年长的员工的薪水。 但使用以下查询我无法获得正确的 id、salary。
SELECT salary.id,employee.Dept,salary.salary,MIN(employee.DoB)
from employee
INNER JOIN salary ON salary.id = employee.id GROUP by Dept
上面的查询返回正确的 Dob,但 ids 和薪水与出生日期不匹配。
如果您正在运行 MySQL 8.0,只需使用 window 函数:
select *
from (
select
e.*,
s.salary,
row_number() over(partition by department order by dob asc) rn_asc,
row_number() over(partition by department order by dob desc) rn_desc
from employee e
inner join salary s on s.id = employee.id
) t
where 1 in (rn_asc, rn_desc)
在早期版本中,一种选择是加入聚合查询:
select e.*, s.salary
from employee e
inner join salary s on s.id = employee.id
inner join (
select department, min(dob) min_dob, max(dob) max_dob
from employee
group by department
) d on d.department = e.department and e.dob in (d.min_dob, d.max_dob)
我想我会在相关子查询中使用=
两次:
select s.*, e.department
from salary join
employee e
on s.id = e.id
where e.dob = (select min(e2.dob) from employee e where e2.department = e.department) or
e.dob = (select max(e2.dob) from employee e where e2.department = e.department) ;
有了employee(department, dob)
的索引,我希望这会有很好的表现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.