leetcode-177-Nth-Highest-Salary

描述


Write a SQL query to get the second highest salary from the Employee table.

1
2
3
4
5
6
7
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+

For example, given the above Employee table, the $n^{th}$ highest salary where n = 2 is 200. If there is no $n{th}$ highest salary, then the query should return null.

分析


和上一题 176-Seconde-Highest-Salary 是相关联的

解决方案(MySQL)


比较容易想到的一个思路是先构造一个集合,把薪水最高的排除出去,这时候再选薪水最高的,就是 Employee 表中薪水第二高的了。

1
2
3
4
5
6
7
8
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
SET N = N-1;
RETURN (
# Write your MySQL query statement below.
SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT N,1
);
END

这里利用了 MySQL 的 limit,offset 关键字,limit 1 的意思是只筛选出一行,offset 1 的意思是从第2行开始,这里即选出表中薪水第二高的 Salary

题目来源