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.
解法一:
# Write your MySQL query statement below
select(select salary from Employee group by salary order by salary desc limit 1,1) as ‘SecondHighestSalary‘;
解法二:
select max(salary)
from Employee
where salary < (select max(salary) from Employee)
要点:
1、去重,所以使用group by进行分组
2、由于要得到第二大工资,所以需要进行排序,
3、max得到的最大值,但是要得到第二个最大值,所以要使用limit 1,1
limit start,len
start 表示页数,0,1,2,3....
len表示页的记录数
4、由于答案的列名是SecondHighestSalary,所以最后要使用as 重命名
5、需要使用两个select,第二个select用于重建列和列值。因为second highest salary 如果不存在的话,那么内部的select返回值是null,不符合答案。因此需要对内部select进行重建列和列值。
原文地址:http://blog.csdn.net/havedream_one/article/details/45394127