SQL查询 第二高的薪水
程序员文章站
2022-07-07 09:47:22
...
编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/second-highest-salary
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/second-highest-salary
思路:当然这个SQL查询关键是null的返回,笔者使用isnull等内置函数没用,猜测可能是应为limit的查询机制问题,最后笔者利用left join 函数自带返回的null值作为切入点编造出sql语句,性能达到73%,虽然不算最优,但还是可以的。
select b.Salary as SecondHighestSalary from Employee as a
left join (select Id,Salary from Employee group by Salary order by Salary DESC limit 1,1) as b
on a.Id = b.Id
order by b.Salary DESC limit 1