SQL求第二高薪水
編寫一個 SQL 查詢,獲取 Employee 表中第二高的薪水(Salary) 。
Id | Salary |
---|---|
1 | 100 |
2 | 200 |
3 | 300 |
例如上述 Employee 表,SQL查詢應該返回 200 作為第二高的薪水。如果不存在第二高的薪水,那麼查詢應返回 null。
SecondHighestSalary |
---|
200 |
解法
一開始的思路,用max()函式查詢兩次
SELECT MAX(e.Salary) AS SecondHighestSalary
FROM Employee e
WHERE e.Salary < (
SELECT MAX(Salary)
FROM Employee
);
但是效率很差,做了兩次查詢
一次結果中查詢第二條
select DISTINCT Salary from Employee ORDER BY Salary DESC limit 1 offset 1;
結果還是不行,DISTINCT 似乎會使返回值為null的時候返回空,所以外層需要巢狀一層
select (select DISTINCT Salary from Employee ORDER BY Salary DESC limit 1 offset 1) as SecondHighestSalary;