【问题标题】:How to write SQL to select rows that has the max(value) of each group?如何编写 SQL 来选择具有每个组的最大值(值)的行?
【发布时间】:2019-12-03 19:59:46
【问题描述】:

表格如下:

employee, department, salary

Jack, 1, 400
Greg, 2, 350
John, 1, 450
Kate, 2, 420
Jane, 3, 300
Jessy, 2, 400
Kevin, 3, 380

我想做的:选择包含各部门最高工资的行,我希望返回:

John,  1, 450
Jessy, 2, 400
Kevin, 3, 380

这里对于部门 1,John 的薪水最高,所以我选择了这一整行。

这个SQL怎么写?

【问题讨论】:

  • 你的 rdbms 是什么? Sql Server、postgres、oracle?
  • 如果一个部门的两个人的最高薪水相同,预期的结果是什么 - 你想要两个人还是一个人?

标签: sql select greatest-n-per-group


【解决方案1】:

一种方法使用相关子查询:

select e.*
from employee e
where e.salary = (select max(e2.salary) from employee e2 where e2.department = e.department);

【讨论】:

    【解决方案2】:

    我通常使用窗口函数来解决这个问题:

    select employee, department, salary
    from (
      select employee, department, salary, 
             dense_rank() over (partition by department order by salary desc) as rnk
      from employee_table
    ) t
    where rnk = 1;
    

    【讨论】:

      【解决方案3】:

      select e1.* from employee e1 where e1.salary in (select max(e2.salary) from employee e2 where e2.department = e1.department);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-20
        • 1970-01-01
        • 2021-07-30
        • 2022-11-13
        • 2021-07-30
        • 2012-01-04
        • 1970-01-01
        相关资源
        最近更新 更多