题目来源:LeetCode
编写一个 SQL 查询,获取并返回 Employee 表中第二高的薪水 。如果不存在第二高的薪水,查询应该返回 null 。
1、题目分析
获取第二高的薪水,需要涉及去重distinct,排序order by和limit限制结果个数
SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC LIMIT 1,1)
但题目中还要求,若不存在第二高的薪水,返回Null,则需要使用ifnull(, null)判断
IFNULL(SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC LIMIT 1,1), null)
2、题目结果
SELECT IFNULL(SELECT DISTINCT salary
FROM Employee
ORDER BY salary DESC LIMIT 1,1), null) AS SecondHighestSalary