leetcode-SQL 184. 部門工資最高的員工(難度:中等)-- 排序函數的使用(rank()/dense_rank())

Employee 表包含所有員工信息,每個員工有其對應的 Id, salary 和 department Id。

+----+-------+--------+--------------+
| 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 查詢,找出每個部門工資最高的員工。例如,根據上述給定的表格,Max 在 IT 部門有最高工資,Henry 在 Sales 部門有最高工資。

+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT         | Max      | 90000  |
| Sales      | Henry    | 80000  |
+------------+----------+--------+

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/department-highest-salary
 

注意: 同一個部門最高工資可能有多個人

排序函數:

ROW_NUMBER OVER(partition by … order by … desc):無並列,相同名次順序排列

RANK OVER(partition by … order by … desc):有並列,跳躍排序,有兩個第二名時後邊跟着的是第四名

DENSE_RANK OVER(partition by … order by … desc):有並列,連續排序,有兩個第二名時仍然跟着第三名

這題用rank() 和 dense_rank() 的結果一樣。


select Department, Employee, Salary
from
(select e.Name Employee, e.Salary Salary, d.Name Department,
dense_rank() over(partition by e.DepartmentId order by Salary desc) ranking
from Employee e 
join Department d
on e.DepartmentId = d.Id) t
where ranking =1;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章