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、4rank()
: 同值同名,有跳级,如 : 3000、2000、2000、1000 , 排名 : 1、2、2、4dense_rank()
: 同值同名,无跳级,如 : 3000、2000、2000、1000 , 排名 : 1、2、2、3
-- 根据 Salary 排序
with t1 as (select Salary,dense_rank() over(order by Salary desc) as r1from Employee
),
-- 选择第二个 , 注意会返回多条 ,用 limit 限制
t2 as (select Salaryfrom t1where r1 = 2limit 1
)
-- 判 null
select ifnull((select Salary from t2), null) as SecondHighestSalary
第二种方法 :
distinct
对同值进行去重 , 再选择第二个- 排除第一个和第二个是同值 , 如 : 3000、3000、2000、1000
with t1 as (select distinct Salaryfrom Employee order by Salary desc limit 1,1
)
-- 判 null
select ifnull((select Salary from t1), null) as SecondHighestSalary;