leetcode176 Second Highest Salary-zh
# 176. 第二高的薪水 (opens new window)
English Version (opens new window)
# 题目描述
编写一个 SQL 查询,获取 Employee
表中第二高的薪水(Salary) 。
+----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+
例如上述 Employee
表,SQL查询应该返回 200
作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null
。
+---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+
# 解法
# SQL
解法 1:使用 LIMIT 语句和子查询。
# Write your MySQL query statement below
SELECT
(
SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1
) AS SecondHighestSalary;
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
解法 2:使用 MAX()
函数,从小于 MAX()
的 Salary 中挑选最大值 MAX()
即可。
# Write your MySQL query statement below
SELECT MAX(Salary) AS SecondHighestSalary
FROM Employee
WHERE Salary < (
SELECT MAX(Salary)
FROM Employee
);
1
2
3
4
5
6
7
2
3
4
5
6
7
编辑 (opens new window)
上次更新: 2021/10/30, 12:58:38