佛系每日养生题176. 第二高的薪水

176. 第二高的薪水

难度中等

编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary)
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+


例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null

+-------------------------------+
| SecondHighestSalary|
+--------------------------------+
| 200 |
+--------------------------------+

方法一:子查询+Limit

如果由两个人的工资都是100,那么不去重的话,数据排序完,返回的第二大值就是100,所以要去重DISTINCT

先将工资倒序排序,然后Limit 1 offset 1可以获得第二高的值

如果该值不存在,返回NULL,故将上查询作为临时表

子查询的特质:子查询数据出虚表嵌套查询虚表,如果查询不到会返回null

SELECT
(SELECT distinct Salary 
from employee
order by Salary desc
limit 1 offset 1) as SecondHighestSalary

方法二:IFNULL+Limit

SELECT
ifnull(
(SELECT distinct Salary 
from employee
order by Salary desc
limit 1 offset 1),
null
) as SecondHighestSalary
posted @ 2021-12-15 22:57  HEREISDAVID  阅读(26)  评论(0)    收藏  举报