LeetCode 176. Second Highest Salary--Database--數據庫題目

LeetCode 176. Second Highest Salary–Database–數據庫題目


LeetCode題解專欄:LeetCode題解
我做的所有的LeetCode的題目都放在這個專欄裏,大部分題目Java和Python的解法都有。


題目地址:Second Highest Salary - LeetCode


Write a SQL query to get the second highest salary from the Employee table.

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.

+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

題目意思很簡單,就是找第二高的工資。

按工資排序的代碼如下:

select distinct Salary as SecondHighestSalary
from Employee
order by Salary desc;

找第二高的代碼:

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;

另外一種解放:

SELECT max(Salary) AS SecondHighestSalary
FROM Employee
WHERE Salary < (SELECT max(Salary) FROM Employee);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章