LeetCode176 & 177. Second/NtH Highest Salary - 第 2/N 高的薪水 <Medium>

本文介绍如何使用SQL查询获取员工表中的第二高薪水,并提供多种解决方案,包括通过排序和限制查询结果的方法,以及通过查找最高薪水之下次高的薪水的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写一个 SQL 查询,获取 Employee 表中第二/N高的薪水(Salary) 。

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null

+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

 

Write a SQL query to get the second highest salary from the Employee table.
For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.

 

第二高薪水,有以下几种思路:

1、可以对薪水进行降序排序,第二高薪水即为第二条记录 -> offset 1,限制返回一条记录 -> limit 1;

2、第二高薪水即最高薪水之下的最高薪水,即排除一个最高薪水后的序列最大值;

# Method 1
select (
    select distinct Salary from Employee order by Salary desc limit 1 offset 1
) as SecondHighestSalary 

select 
    IFNULL((select distinct Salary from Employee order by Salary desc limit 1 offset 1),NULL) 
as SecondHighestSalary
# Method 2
select Max(Salary) as SecondHighestSalary
from Employee
where Salary < (select Max(Salary) from Employee)

 

Plus 第N高薪水解法; 注:limit 1 offset N 即跳过N个元素,向后取一个元素,等价于limit N,1

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  set N = N-1;
  RETURN (
      # Write your MySQL query statement below.
        select IFNULL((select distinct Salary from Employee order by Salary desc limit 1 offset N),NULL) as SecondHighestSalary 
      );
END

另解:Employee两张临时表a、b,b表中有N-1条a表大的数据时,a表的MAX(Salary)为第N高薪;

select MAX(Salary) as getNthHighestSalary from Employee a
where N -1 =
(select count(distinct b.Salary) from Employee b where b.Salary > a.Salary)

第二高薪即:

select MAX(Salary) as SecondHighestSalary from Employee a
where 1 =
(select count(distinct b.Salary) from Employee b where b.Salary > a.Salary)

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值