#Leetcode Database
177. Nth Highest Salary
URL: https://leetcode.com/problems/nth-highest-salary/
Write a SQL query to get the nth highest salary from the Employee
table.
+----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+
For example, given the above Employee table, the nth highest salary where n = 2 is 200
. If there is no nth highest salary, then the query should return null
.
+------------------------+ | getNthHighestSalary(2) | +------------------------+ | 200 | +------------------------+
这个题跟176. Second Highest Salary 方法类似,只是将查询过程写到了一个函数中,用了 CREATE FUNCTION
【Solution 1】:
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
DECLARE tmp_N INT; //声明一个变量tmp_N
SET tmp_N = N-1; // 因为之后用到 limit... offset ..从取第Nth最高的工资,所以从第N-1行开始
Return(
Select DISTINCT Salary
From Employee order by Salary Desc
limit 1 Offset tmp_N);
END
【Soultion 2】:
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
Return(
SELECT Salary
FROM (SELECT Distinct Salary, DENSE_RANK() OVER ( ORDER BY Salary DESC my_rank FROM Employee) AS tmp WHERE my_rank = N
);
END
【Note】:
①LIMIT n1 OFFSET n2 从第n2行开始(不包含n2)取n1行数据
eg: Select * from student limit 3 offset 10 从第10行开始往下去3行,即 11,12,13行的数据
②RANK() OVER() 和 DENSE_RANK() OVER()
RANK() OVER( ORDER BY 排序的字段名) : 如果出现并列情况,则排名相同,下一个数据排名延后。那么 排名的数字顺序为不连续。
eg 成绩排名,100 为 Rank = 1, 99,99出现两次,RANK均为2, 下一个96,RANK = 4。 (RANK=3的情况不会显示)RANK的数字非连续。
DENSE_RANK() OVER(ORDER BY 排序的字段名) 区别在于 在并列情况下,RANK的数字连续,
eg 成绩排名,100 为 Rank = 1, 99,99出现两次,RANK均为2, 下一个96,RANK = 3。 (RANK=3的情况不会显示)RANK的数字连续。
③CREATE FUNCTION 用法:
语句如下:
CREATE FUNCTION function_name [ (parameter datatype [, parameter datatype]) ] RETURNS return_datatype
BEGIN
declaration_section //声明变量
executable_section
END;