我正在尝试解决LeetCode问题https://leetcode.com/problems/second-highest-salary/description/;到目前为止我的解决方案(另见http://sqlfiddle.com/#!9/4752cb/1)是:
SELECT Salary AS SecondHighestSalary
FROM Employee
ORDER BY Salary DESC LIMIT 1, 1;
问题是我的解决方案在以下测试用例中失败了:
换句话说,它只返回没有结果而不是返回NULL
。如果没有第二高薪,我如何让它返回NULL
?
更新
在Return a value if no record is found之后,我尝试将查询封装在子查询中:
SELECT (SELECT Salary
FROM Employee
ORDER BY Salary DESC LIMIT 1, 1) AS SecondHighestSalary;
但是,在另一个具有相同薪水的两名员工的测试案例中,这个失败了:
在这种情况下,我们显然也应该返回NULL
。我如何调整上面的'更接近解决方案'查询来处理这个问题?
答案 0 :(得分:2)
使用union all
选择另一行返回null,以便保留顺序,然后只返回第一行:
SELECT * FROM
(
SELECT Salary AS SecondHighestSalary
FROM Employee
ORDER BY Salary DESC LIMIT 1, 1
UNION ALL
SELECT NULL
)
LIMIT 1
答案 1 :(得分:1)
这里OFFSET 1表示没有第一个(EX:如果你不想先显示2,那么OFFSET将是2)
SELECT
Salary AS SecondHighestSalary
FROM
Employee
ORDER BY
Salary
LIMIT 1 OFFSET 1;
答案 2 :(得分:1)
使用当前查询,我们可以将其包装在另一个查询中,并使用聚合函数
SELECT MAX(v.salary) AS SecondHighestSalary
FROM (
SELECT e.Salary
FROM Employee e
ORDER BY e.Salary DESC
LIMIT 1, 1
) v
这套第二高薪应该是什么......
id salary
-- ------
1 1000
2 1000
4 750
我们应该返回1000,还是返回750?如果我们想要返回750,我们可以这样做:
SELECT MAX(s.salary) AS SecondHighestSalary
FROM ( SELECT MAX(e.salary) AS max_salary
FROM Employee e
) h
JOIN Employee s
ON s.salary < h.max_salary
答案 3 :(得分:1)
这是一个最终通过测试的查询:
SELECT (SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary DESC LIMIT 1, 1) AS SecondHighestSalary;
它似乎比其他解决方案更直观,不是吗?
答案 4 :(得分:0)
Safe with Distinct不包括空值:
SELECT distinct Salary AS SecondHighestSalary
FROM Employee where salary is not null ORDER BY salary desc limit 1,1
答案 5 :(得分:0)
使用
ifnull :
SELECT ifnull(
(select distinct salary from Employee order by salary desc limit 1,1),
NULL
)) AS "SecondHighestSalary"
如果第一个查询什么都不返回,则返回NULL。
答案 6 :(得分:0)
您可以首先获取前两个值 然后分别处理null和一般情况
select case
when min(top2.salary)=max(top2.salary) then null
else min(top2.salary) end
as SecondHighestSalary
from
(select e.salary from employee e order by e.salary desc limit 2) as top2;