题目
链接:https://leetcode-cn.com/problems/second-highest-salary)
编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
解法
解法一:
对Salary去重,排序后查找排名第二的Salary,查找时使用limit函数在排序后的列表中查找。
select IFNULL((select distinct Salary
from Employee
order by Salary desc
limit 1,1),null )as SecondHighestSalary
解法二:
第二高,即除掉最大值的范围中最大的值。故只需要找到小于最大值范围中的最大值即可。
select MAX(Salary) as SecondHighestSalary
from Employee
where Salary < (
select MAX(Salary)
from Employee
)
举一反三:
Q:如果需要返回 薪水第二高的 员工信息,如何做?
A:使用窗口函数 dense_rank(),找到所有排名为2的员工信息。
dense_rank()是允许并列排名,但为依次排名的窗口函数。(即面对并列情况,排名为1,2,2,3)
select *
from (select *,dense_rank() over(Order by Salary desc) as ranking
from employee)as A
where ranking=2
说明:为什么不向下式这样写?
select *,dense_rank() over(Order by Salary desc) as ranking
from employee
where ranking=2
因为select子句的运行顺序在where子句之后的,在where子句运行时ranking这一列还没被定义。通过在from子句中使用子查询,相当利用窗口函数建立了一个新表。