牛客-sql18 非order by 查找第N

本文介绍了两种方法:一是通过嵌套查询找出原表外的第二高工资,二是利用工资表自连接找出工资等于第二高的人。两种思路都展示了如何在SQL中筛选出特定工资范围的员工信息。

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

题目: sql18

思路一:

  1. 查找原表最高工资
  2. 查找除原表最高工资的情况下,查找原表第二高工资
  3. 筛选工资等于第二高工资的人员信息
select s.emp_no, s.salary, e.last_name, e.first_name
from salaries s join employees e
on s.emp_no = e.emp_no
where s.salary =              -- 第三步: 将第二高工资作为查询条件
    (
    select max(salary)        -- 第二步: 查出除了原表最高工资以外的最高工资(第二高工资)
    from salaries
    where salary <   
        (
        select max(salary)    -- 第一步: 查出原表最高工资
        from salaries
        where to_date = '9999-01-01'  
        )
    and to_date = '9999-01-01'
    )
and s.to_date = '9999-01-01'

思路二:

  1. 工资表自连接查询,group by 左表工资,havin条件:去重右表工资后 个数=2
  2. 筛选工资等于第二高工资的人员信息
select e.emp_no
, salary
, last_name
, first_name
from employees e 
join salaries s 
on e.emp_no = s.emp_no 
where s.salary = 
(
    select s1.salary 
    from salaries s1 
    join salaries s2 
    on s1.salary <= s2.salary 
    where s1.to_date='9999-01-01'
    and s2.to_date='9999-01-01'
    group by s1.salary
    having count(distinct s2.salary) = 2   -- !!!!!!!!!!!
)
and s.to_date='9999-01-01'

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值