SQL(部门薪资最高的员工)

  • Post author:
  • Post category:其他


Employee表:

ID Name Salary DepartmentId
1001 Emma 12000 1
1002 Alex 13000 2
1003 Tom 9000 3
1004 Star 11000 1
1005 Eric 15000 2

Department表:

ID Name
1 IT
2 Sales
3 Finance

编写一个SQL语句,找出每个部门薪资最高的员工。

应得查询结果如下:

Department Employee Salary
IT Emma 12000
Sales Eric 15000
Finance Tom 9000
#分解步骤:
#找到每个部门薪资最高的信息(表a)
select max(Salary) ms,DepartmentId from Employee group by DepartmentId
#找到每个部门最高薪资对应的员工信息(表b)
select e.Name,e.Salary,e.DepartmentId from Employee e,a where e.Salary=a.ms and e.DepartmentId=a.DepartmentId
#找到对应的部门名称
select d.name Department,b.name Employee,Salary from  b , Department d where b.DepartmentId =d.id;
#整合
select d.name Department,b.name Employee,Salary from (
    select e.Name,e.Salary,e.DepartmentId from Employee e,
    (select max(Salary) m,DepartmentId from Employee group by DepartmentId) a
    where e.Salary =a.m and e.DepartmentId =a.DepartmentId) b , Department d where
b.DepartmentId =d.id;



版权声明:本文为gly1653810310原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。