Second Highest Salary
阿新 • • 發佈:2018-12-31
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 | +---------------------+
解題思路:
注意兩點:首先如果沒有第二高的工資,應該返回NULL,如果直接使用查詢會查詢為空,而不會返回NULL,所以需要將此查詢作為子查詢。
第二點是找第二高的工資,是工資多少排第二,而不是工資排名第二,所以需要distinct修飾。
select (select distinct Salary from Employee order by Salary desc limit 1,1) as SecondHighestSalary;