LeetCode:176.第二高的薪水
题目链接:https://leetcode-cn.com/problems/second-highest-salary/
题目
编写一个 SQL 查询,获取 Employee
表中第二高的薪水(Salary)
。
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
例如上述 Employee
表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null
。
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
解答
第一次解答报错。。。
---- oracle ----
/* Write your PL/SQL query statement below */
select Salary as SecondHighestSalary
from
(
select Salary,
rownum as rn
from
(
select Salary
from Employee
order by Salary desc
) b
) c
where c.rn = 2 ---- 执行报错 当数据只有1行时 执行为空 而不是null
第二次解答。。。依旧报错
---- oracle ----
/* Write your PL/SQL query statement below */
select Salary as SecondHighestSalary
from
(
select Salary,
row_number() over(order by Salary desc) as rn
from Employee
) c
where c.rn = 2 ---- 依旧报错
参考评论之后,再改进。。
解答一
---- oracle ----
/* Write your PL/SQL query statement below */
select max(Salary) as SecondHighestSalary
from Empolyee
where Salary <> (select max(Salary) from Employee) ---- 672ms
解答二
修改第一次出错的版本,添加判断后再次尝试。。。
---- oracle ----
select Salary as SecondHighestSalary
from
(
select Salary
from
(
select Salary,
rownum as rn
from
(
select distinct(Salary)
from Employee
order by Salary desc
) b
) c
where c.rn = 2
union all
select null from dual
)
where rownum = 1 -- 未针对薪水进行去重操作 增加distinct
-- 不添加distinct还执行报错 添加之后通过
---- 861ms
解答三
好久没用过MySQL
,用法都忘光了。。
使用子查询和LIMIT
子句
---- MySQL ----
select
(
select distinct Salary
from Employee
order by Salary desc
limit 1 offset 1
) as SecondHighestSalary; ---- 112ms 好快
解答四
为了解决NULL
的问题,可以使用IFNULL
函数
---- MySQL ----
select
ifnull(
(
select distinct Salary
from Employee
order by Salary desc
limit 1 offset 1
),
NULL) as SecondHighestSalary ---- 108ms
思考
去重、排序、获取第二个、返回为NULL
时设置返回NULL
注意
oracle中rownum
的使用必须要包含第一条记录,也就是类似rownum <= 10
,所以不能使用rownum = 2
提取第2行数据,必须利用嵌套查询实现。
group by
的速度比distinct
速度要快。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)