Employee
表包含所有員工信息,每個員工有其對應的 Id, salary 和 department Id。
Department
表包含公司所有部門的信息。
編寫一個 SQL 查詢,找出每個部門工資最高的員工。
第一版sql:
select Department.name as Department,Employee.Name as Employee,max(Salary) as Salary from Employee left join Department on Department.Id = Employee.DepartmentId group by DepartmentId
輸出結果:
發現最高薪資查出來了,但是名字和薪資對不上
第二版sql:
select d.name as Department,e.name as Employee,Salary from Employee e inner join Department d on e.DepartmentId=d.id where e.Salary>=(select max(Salary) as Salary from Employee where DepartmentId = d.id )
輸出結果正確。
第三版:
先查出部門最高工資的思路
select d.name as department,e.name,e.salary from employee e left JOIN (select id,max(salary) as salary,departmentid from employee GROUP by departmentid)c on e.DepartmentId=c.DepartmentId left JOIN department d on e.departmentid= d.id where e.departmentid = c.departmentid and e.salary = c.salary
執行結果
結果正確。
參考:https://blog.csdn.net/qq_43048011/article/details/82193952