力扣176. 第二高的薪水

力扣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                 |
+---------------------+

法一:

# Write your MySQL query statement below
select 
(select distinct Salary  #distinct 返回唯一不同的值
from Employee 
order by Salary desc#降序排列
limit 1,1)#第二高   
#limit x,y ,是跳过x行,取y行数据的意思,类似于 limit y offset x, 而不是类似于 limit x offset y。 limit x offset y是跳过y行,取x行数据
as SecondHighestSalary;#看成一张临时表

法二:

ifnull语句

select 
(
    ifnull
    (
        (select distinct salary #distinct 返回唯一不同的值
        from employee 
        order by salary desc #降序排列
        limit 1,1)
    ,null)
    #limit x,y ,是跳过x行,取y行数据的意思,类似于 limit y offset x, 而不是类似于 limit x offset y。 limit x offset y是跳过y行,取x行数据
)
as SecondHighestSalary;#看成一张临时表
发布了23 篇原创文章 · 获赞 0 · 访问量 137

猜你喜欢

转载自blog.csdn.net/qq_35683407/article/details/105424698