[英]How to write SQL to select rows that has the max(value) of each group?
The table is like below: 表格如下:
employee, department, salary
Jack, 1, 400
Greg, 2, 350
John, 1, 450
Kate, 2, 420
Jane, 3, 300
Jessy, 2, 400
Kevin, 3, 380
I wish to do: Select the row that contains the highest salary of each department, I expect to return: 我希望这样做:选择包含每个部门最高薪水的行,我希望返回:
John, 1, 450
Jessy, 2, 400
Kevin, 3, 380
Here for department 1, John has the highest salary, so I select this whole row. 在这里,部门1,约翰的薪水最高,所以我选择这整行。
How to write this SQL? 怎么写这个SQL?
One method uses a correlated subquery: 一种方法使用相关子查询:
select e.*
from employee e
where e.salary = (select max(e2.salary) from employee e2 where e2.department = e.department);
从员工e1的e1.salary中选择e1。*(从员工e2的e2.department = e1.department中选择max(e2.salary));
I typically solve that using window functions: 我通常使用窗口函数解决此问题:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.