面試題:查詢部門最高工資的員工資訊
阿新 • • 發佈:2019-01-07
難度:中等
表Employee儲存了所有的員工資料。
Id | Name | Salary | DepartmentId |
---|---|---|---|
1 | Joe | 70000 | 1 |
2 | Henry | 80000 | 2 |
3 | Sam | 60000 | 2 |
4 | Max | 90000 | 1 |
表Department儲存了所有的部門資料。
Id | Name |
---|---|
1 | IT |
2 | Sales |
寫一段SQL查找出各部門工資最高的員工資訊。如上所示,IT部門工資最高的是Max,Sales部門工資最高的是Henry。
Department | Employee | Salary |
---|---|---|
IT | Max | 90000 |
Sales | Henry | 80000 |
- 答案一:
SELECT D.Nameas Department, E1.Name as Employee, E1.Salary as Salary
FROM Employee E1 join Department D
WHERE E1.DepartmentId = D.Id and E1.Salary >= (SELECT MAX(Salary) from Employee E2 WHERE E1.DepartmentId = E2.DepartmentId);
- 答案二:
SELECT b.Nameas Department,a.nameas Employee, a.Salaryas Salary
FROM Employee a, Department b, (select max(Salary) as Salary, DepartmentId from Employee group by DepartmentId) c
WHERE a.DepartmentId = b.Id and a.Salary = c.Salary and a.DepartmentId = c.DepartmentId