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