数据库:第二高的薪水

题目链接: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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值