題目正文
編寫一個 SQL 查詢,獲取 Employee 表中第二高的薪水(Salary) 。
+----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+
例如上述 Employee 表,SQL查詢應該返回 200 作為第二高的薪水。如果不存在第二高的薪水,那麼查詢應返回 null。
+---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+
解題思路
這道題目不難,有很多解題方案,這邊接受一種 limit 和 offset的。
錯誤解答
select distinct salary as SecondHighestSalary from Employee order by salary DESC limit 1 offset 1;
這個是第一個想到的解法,不過未能通過,原因在處理不存在第二高的時候,未輸出null,而是無輸出。
解答
select ( select distinct Salary from Employee order by Salary desc limit 1 offset 1) as SecondHighestSalary;