【问题标题】:Query to find second highest value per group查询以查找每组的第二高值
【发布时间】:2021-09-29 17:00:22
【问题描述】:

编写查询提取部门和每个部门的第二高薪

员工

| Column         | Value          |
| -------------- | -------------- |
| employee_id    | int            |
| name           | string         |
| department     | string         |
| employment_type| string         |
| salary         | int            |

Table Image

【问题讨论】:

  • 你有什么问题?听起来像家庭作业。到目前为止,您自己尝试过什么?

标签: sql greatest-n-per-group


【解决方案1】:

使用窗口函数:

select e.department,
       max(case when seqnum = 2 then e.salary end) as second_highest
from (select e.*,
             dense_rank() over (partition by department order by salary desc) as seqnum
      from employee e
     ) e
group by e.department;

您可以阅读有关 dense_rank() 功能的文档。在这种情况下,它将“1”分配给薪水最高的行,将“2”分配给第二高的行,依此类推。

【讨论】:

    【解决方案2】:

    我认为这可以帮助你。

    SELECT department, MAX(salary) AS second_high FROM Employee
    WHERE second_high < (SELECT MAX(salary) FROM Employee)
    GROUP BY department
    

    【讨论】:

    • 请加解释,让SP能看懂
    猜你喜欢
    • 2022-11-16
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多