力扣-第二高的薪水

大家好,我是空空star,本篇带大家了解一道中等的力扣sql练习题。


前言


一、题目:176. 第二高的薪水

Employee 表:

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| salary      | int  |
+-------------+------+
id 是这个表的主键。
表的每一行包含员工的工资信息。

编写一个 SQL 查询,获取并返回 Employee 表中第二高的薪水 。如果不存在第二高的薪水,查询应该返回 null 。

查询结果如下例所示。

示例1:

输入:
Employee 表:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+
输出:
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+


示例 2:

输入:
Employee 表:
+----+--------+
| id | salary |
+----+--------+
| 1  | 100    |
+----+--------+
输出:
+---------------------+
| SecondHighestSalary |
+---------------------+
| null                |
+---------------------+


二、解题

1.正确示范①

提交SQL

select salary SecondHighestSalary from(
select salary,row_number() over(order by salary desc ) col
from(
select
salary
from Employee
union
select null
) u
) u
where col=2;

运行结果

2.正确示范②

提交SQL

select salary SecondHighestSalary from(
select salary,rank() over(order by salary desc ) col
from(
select
salary
from Employee
union
select null
) u
) u
where col=2;

运行结果

3.正确示范③

提交SQL

select salary SecondHighestSalary from(
select salary,dense_rank() over(order by salary desc ) col
from(
select
salary
from Employee
union
select null
) u
) u
where col=2;

运行结果

4.正确示范④

提交SQL

select ifnull(
(select distinct salary from Employee
order by salary desc limit 1 offset 1),
null) as SecondHighestSalary;

运行结果

5.其他


总结

正确示范①思路:
考虑到工资可能重复以及不存在第二高的薪水时查询应该返回 null ,
我们做如下处理:
select salary from Employee union select null
然后再采用row_number() over(order by salary desc ) col,限定col=2;
正确示范②思路:
考虑到工资可能重复以及不存在第二高的薪水时查询应该返回 null ,
我们做如下处理:
select salary from Employee union select null
然后再采用rank() over(order by salary desc ) col,限定col=2;
正确示范③思路:
考虑到工资可能重复以及不存在第二高的薪水时查询应该返回 null ,
我们做如下处理:
select salary from Employee union select null
然后再采用dense_rank() over(order by salary desc ) col,限定col=2;
正确示范④思路:
对工资通过distinct去重后,
通过 order by salary desc按工资降序,
通过limit 1 offset 1跳过1条数据,读取1条数据,
再通过ifnull(表达式,null)做空时返回null处理。
知识点:
row_number:顺序排序;
rank:并列排序,会跳过重复的序号,比如序号为1、1、3;
dense_rank:并列排序,不会跳过重复的序号,比如序号为1、1、2。
limit y 表示: 读取前y 条数据
limit x, y 表示: 跳过 x 条数据,读取 y 条数据
limit y offset x 表示: 跳过 x 条数据,读取 y 条数据

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

空空star

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值