Second Highest Salary
來源:程序員人生 發(fā)布時間:2015-05-27 07:48:44 閱讀次數(shù):3007次
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 second highest salary is 200. If there is no second highest salary, then the query should return null.
解法1:
# Write your MySQL query statement below
select(select salary from Employee group by salary order by salary desc limit 1,1) as 'SecondHighestSalary';
解法2:
select max(salary)
from Employee
where salary < (select max(salary) from Employee)
要點:
1、去重,所以使用group by進行分組
2、由于要得到第2大工資,所以需要進行排序,
3、max得到的最大值,但是要得到第2個最大值,所以要使用limit 1,1
limit start,len
start 表示頁數(shù),0,1,2,3....
len表示頁的記錄數(shù)
4、由于答案的列名是SecondHighestSalary,所以最后要使用as 重命名
5、需要使用兩個select,第2個select用于重建列和列值。由于second highest salary 如果不存在的話,那末內部的select返回值是null,不符合答案。因此需要對內部select進行重建列和列值。
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈