176. Second HIghest Salary

176 Second highest salary (第二高的薪水)

题目描述

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

Employee表数据:

Id   Salary  
1 100
2 200
3 300

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

SecondHighestSalary  
200

思路:

  解法一: 通过调用max函数来获取最大值

  解法二:通过distinct来去掉重复数据,并通过limit来获取第二高的薪水

代码实现

# Write your MySQL query statement below
-- 解法一: 通过调用max函数来获取最大值
select max(Salary) as SecondHighestSalary 
from Employee 
where Salary < (select max(Salary) from Employee);
-- 解法二: 通过IFNULL函数。IFNULL(expr1, expr2): 如果expr1不是NULL,就返回expr1,否则就返回expr2
select IFNULL((select Distinct Salary from Employee Order by Salary Desc Limit 1,1), null) as SecondHighestSalary;

 

猜你喜欢

转载自www.cnblogs.com/mrjoker-lzh/p/9775035.html