题目链接:https://leetcode-cn.com/problems/second-highest-salary/
sql架构
Create table If Not Exists Employee (id int, salary int)
Truncate table Employee
insert into Employee (id, salary) values ('1', '100')
insert into Employee (id, salary) values ('2', '200')
insert into Employee (id, salary) values ('3', '300')
Employee 表:
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| salary | int |
+-------------+------+
id 是这个表的主键。
表的每一行包含员工的工资信息。
编写一个 SQL 查询,获取并返回 Employee 表中第二高的薪水 。如果不存在第二高的薪水,查询应该返回 null 。
查询结果如下例所示。
示例1:
输入:
Employee 表:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
输出:
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
示例2:
输入:
Employee 表:
+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
+----+--------+
输出:
+---------------------+
| SecondHighestSalary |
+---------------------+
| null |
+---------------------+
#method1
#分页查询
select ifNull(
(
select distinct Salary
from Employee
order by Salary desc limit 1,1
),null
) as SecondHighestSalary
select coalesce(
(
select distinct Salary
from Employee
order by Salary desc limit 1,1
),null
) as SecondHighestSalary
#method2
#过滤
select max(Salary) SecondHighestSalary
from employee
where
salary<(select max(salary) from employee)
select max(salary) SecondHighestSalary
from employee
where salary not in(
select max(salary)
from employee
order by salary
)
#method3
#不是最大数的最大数
select max(Salary) SecondHighestSalary
from Employee
where Salary != (
select max(Salary) from Employee
)
#method4
#窗口函数
select(
select
salary
from (
select
distinct(salary),
rank() over(order by salary desc) rk
from Employee
) a where rk = 2
) as SecondHighestSalary
#method5
#分组
select
(
select e1.Salary
from Employee e1,Employee e2
where e1.Salary<=e2.Salary
group by e1.Salary
having count(distinct e2.Salary)=2
) as SecondHighestSalary
select
(
select distinct e1.Salary
from Employee e1,Employee e2
group by e1.Id,e1.Salary
having sum(e1.Salary<e2.Salary)=1
) as SecondHighestSalary