SQL 176. 第二高的薪水

SQL 176. 第二高的薪水

SQL 题目地址 : https://leetcode.cn/problems/second-highest-salary/

准备数据

CREATE TABLE `Employee` (
  `Id` int(11) NOT NULL,
  `Salary` int(11) NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB;

insert into Employee values(1, 100), (2, 200), (3,300);

需求

查询第二高的薪水(Salary)

返回结果 :

  • 返回 200 作为第二高的薪水
  • 不存在第二高的薪水,就返回 null
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

解决

重点了解 :

  • row_number() : 同值不同名,类似行号,如 : 3000、2000、2000、1000 , 排名 : 1、2、3、4
  • rank() : 同值同名,有跳级,如 : 3000、2000、2000、1000 , 排名 : 1、2、2、4
  • dense_rank() : 同值同名,无跳级,如 : 3000、2000、2000、1000 , 排名 : 1、2、2、3
-- 根据 Salary 排序
with t1 as (
  select Salary,
    dense_rank() over(order by Salary desc) as r1
  from Employee
),
-- 选择第二个 , 注意会返回多条 ,用 limit 限制
t2 as (
    select Salary
    from t1
    where r1 = 2
    limit 1
)
-- 判 null
select ifnull((select Salary from t2), null) as SecondHighestSalary

第二种方法 :

  • distinct 对同值进行去重 , 再选择第二个
  • 排除第一个和第二个是同值 , 如 : 3000、3000、2000、1000
with t1 as (
  select distinct Salary
  from Employee 
  order by Salary desc limit 1,1
)
-- 判 null
select ifnull((select Salary from t1), null) as SecondHighestSalary;

猜你喜欢

转载自blog.csdn.net/qq_44226094/article/details/129996334