SQL 查询,求第二高的薪水(Salary)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/liminghui4321/article/details/102763082

编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。

±—±-------+
| Id | Salary |
±—±-------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
±—±-------+
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。

±--------------------+
| SecondHighestSalary |
±--------------------+
| 200 |
±--------------------+

解决思路:

select tmp.id,tmp.salary
from (
select *,rank() over(order by salary desc) as rk from employee) tmp
where tmp.rk=2
union all
select null as id,null as salary where not exists(
select *,rank() over(order by salary desc) as rk from employee having rk=2)

猜你喜欢

转载自blog.csdn.net/liminghui4321/article/details/102763082