Search code examples
mysqlsqlinner-joingreatest-n-per-groupmysql-5.6

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


I was given the below question to solve.enter image description here

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.


Solution

  • 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
    )