[英]How to write SQL to select rows that has the max(value) of each group?
表格如下:
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,約翰的薪水最高,所以我選擇這整行。
怎么寫這個SQL?
一種方法使用相關子查詢:
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));
我通常使用窗口函數解決此問題:
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.