Letcode---SQL练习---Second Highest Salary

编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。

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

SQL代码:

select IFNULL((select distinct(Salary)
from Employee
order by Salary desc
limit 1,1),null) as SecondHighestSalary

学到了一个sql函数IFNULL,该函数的作用是判断查询结果集是否为空,若为空则返回第二个参数

还有一种做法,直接用两个select解决

select(select distinct(Salary) from Employee
order by(Salary) desc
limit 1,1) as SecondHighestSalary

 

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务