第N高薪水(利用窗口函数)
利用窗口函数:
ROW_NUMBER() OVER(PARTITION BY Attribution_n1, Attribution_n2,... ORDER BY Attribution_m1,Attribution_m2,...) RANK() OVER(PARTITION BY Attribution_n1, Attribution_n2,... ORDER BY Attribution_m1,Attribution_m2,...) DENSE_RANK() OVER(PARTITION BY Attribution_n1, Attribution_n2,... ORDER BY Attribution_m1,Attribution_m2,...)
-
ROW_NUMBER() 排序的结果连续且不重复
-
RANK() 排序的结果跳跃且重复
-
DENSE_RANK() 排序的结果跳跃重复,且连续
下面按照Salary进行升序排序,可见上述3个窗口函数的结果如下:
Salary | Row_number | Rank | Dense_rank |
100 | 1 | 1 | 1 |
200 | 2 | 2 | 2 |
200 | 3 | 2 | 2 |
300 | 4 | 4 | 3 |
例题:求第N高薪水,如果有则返回薪水,没有则返回NULL。[题目链接]
题解:需要判断是不是存在第N高的薪水。
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT BEGIN RETURN ( # Write your MySQL query statement below. WITH TB(Salary,ID) AS( SELECT Salary, DENSE_RANK()OVER(ORDER BY Salary DESC) AS ID FROM Employee ) SELECT CASE WHEN MAX(ID)>= N THEN (SELECT DISTINCT Salary FROM TB WHERE ID=N) ELSE NULL END from TB ); END
例题:178.分数排名 [题目链接]
如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。
题解:
# Write your MySQL query statement below SELECT Score, DENSE_RANK()OVER(ORDER BY Score DESC) AS "Rank" FROM Scores