leetcode-176-Second-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 second highest salary is 200. If there is no second highest salary, then the query should return null.

分析


题意是查询出 Employee 表中薪水第二高的 Salary 的值。

解决方案(MySQL)


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

1
2
# Write your MySQL query statement below
SELECT MAX(Salary) as SecondHighestSalary FROM Employee WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee)

论坛里有人 po 出了比较正确的做法。上面的做法对于排第二,第三可能没有什么问题,如果是要找出排第四,第五的等等可能就不太适用了,正确的做法是排序后直接选出 $n^{th}$。在 MySQL 里面可以这样做:

1
2
# Write your MySQL query statement below
SELECT (SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1) AS SecondHighestSalary

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

关于 SQL 的连接,可以参考:连接)

题目来源