简体   繁体   中英

Getting the maximum salary getter and his/her department from separate tables

I was given the below question to solve. 在此处输入图像描述

What I tried:

  1. I thought to join all the three tables together. But I'm facing challenges in getting the maximum salary for each department.
select e.empName, d.deptName
from employee e
  join department d on e.deptId = d.deptId
  join salary s on e.empId = s.EmpId
where s.salary = (select max(salary) from salary s)
group by d.deptid;

I referred these answers also but I'm not able to implement them according to my needs.

  1. join-multiple-columns-from-one-table-to-single-column-from-another-table
  2. sql-select-only-rows-with-max-value-on-a-column
  3. select-emp-with-max-sal-from-each-dept

This is my sql fiddle link. I am using MYSQL version 5.6 SQL FIDDLE

Any suggestions would be helpful.

You can use rank() :

select *
from (
    select e.empName, d.deptName, s.salary, 
        rank() over(partition by d.deptId order by s.salary desc) rn
    from employee e 
    join department d on e.deptId = d.deptId
    join salary s on e.empId = s.EmpId
) t
where rn = 1

This requires MySQL 8.0. In earlier versions of MySQL, you would use a correlated subquery:

select e.empName, d.deptName, s.salary
from employee e 
join department d on e.deptId = d.deptId
join salary s on e.empId = s.EmpId
where s.salary = (
    select max(s1.salary)
    from salary s1
    join employee e1 on e1.empId = s1.empId
    where e1.deptId = d.deptId
)

This is a good place to use window functions:

select empName, deptName
from (select e.empName, d.deptName, s.salary,
             max(s.salary) over (partition by d.deptName) as max_salary
      from employee e join
           department d
           on e.deptId = d.deptId join
           salary s
           on e.empId = s.EmpId 
     ) ed
where salary = max_salary;

Here is a db<>fiddle.

select *
from (
    select *,
       ROW_NUMBER() OVER (PARTITION BY d.deptId ORDER BY s.salary DESC) rn
    from employee e 
    join department d on e.deptId = d.deptId
    join salary s on e.empId = s.EmpId
) tbl
where rn = 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM