编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。
+----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
代码
select (select distinct Salary from Employee order by Salary DESC limit 1,1) As SecondHighestSalary
或者
select (select Salary from Employee group by Salary order by Salary DESC limit 1,1) As SecondHighestSalary
解析
Select Salary from Employee 从表 Employee 中查询 Salary
group by Salary Salary 分组,去重,过滤掉重复的
order by Salary DESC Salary 倒序
limit X,Y 中X表示跳过X个数据,读取Y个数据
Select * As SecondHighestSalary 是把 * 号当做一个临时表,如果查询不到,就返回null
distinct Salary 去重,过滤掉重复的