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速度要快。

猜你喜欢

转载自www.cnblogs.com/hider/p/11721172.html