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);