Reputation: 46
I was given the below question to solve.
What I tried:
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.
This is my sql fiddle link. I am using MYSQL version 5.6 SQL FIDDLE
Any suggestions would be helpful.
Upvotes: 0
Views: 1008
Reputation: 222432
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
)
Upvotes: 2
Reputation: 701
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
Upvotes: 1
Reputation: 1269613
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.
Upvotes: 1