题目描述
编写一个SQL
查询,获取Employee
表中的第二高的薪水(Salary)。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述的Employee
表中,SQL
查询应该返回200
作为第二高的薪水。
如果不存在第二高的薪水,那么就返回null
。
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
算法设计与分析:
方法一:使用子查询和LIMIT
子句
- 算法:将不同的薪资按照降序进行排序,然后使用
LIMIT
子句获得第二高的薪资。
select distinct
Salary as SecondHighestSalary
from
Employee
order by Salary desc
limit 1 offset 1
注意: 如果这样做,但是没有第二高的工资,这个解决方案就会被判断为“错误方案”,因为本表可能只有一项纪录。为了克服这个问题,我们可以将其作为临时表。
select
(select distinct
Salary
from
Employee
order by Salary desc
limit 1 offset 1) as SecondHighestSalary
;
方法二:使用IFNULL
和LIMIT
子句
解决“NULL”问题的另外一种方法是使用“IFNULL”函数:
select
IFNULL(
(select distinct
Salary
from
Employee
order by
Salary
limit 1 offset 1),NULL)
as
SecondHighestSalary
一些技巧性的东西要积累:
- distinct :去除重复的值,因为返回的值可能会包含重复的值,本题如果不加,就通不过他那个设置重复值的测试用例。
- IFNULL(xxx,null) :返回空值处理
- AS xxx :取别名
- limit 1 offset 1 :取第二条
- order by xxx desc: 按照字段xxx降序排序
注: 本题解参考到leetcode官方题解。