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.
How to write this 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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.