185. 部门工资前三高的所有员工 + 多表联合 + join + dense_rank()
185. 部门工资前三高的所有员工
LeetCode_MySql_185
题目描述
方法一:使用join on
# Write your MySQL query statement below
select d.Name as 'Department', e1.Name as 'Employee', Salary
from Employee e1 join Department d on e1.DepartmentId = d.Id
where
3 >( # 查找工资高于e1.Salary的个数
select count(distinct Salary)
from Employee e2
where e1.DepartmentId = e2.DepartmentId
and e1.Salary < e2.Salary
);
方法二:使用dense_rank() over
# Write your MySQL query statement below
/**
解题思路:先对Employee表进行部门分组工资排名,再关联Department表查询部门名称,再使用WHERE筛选出排名小于等于3的数据(也就是每个部门排名前3的工资)。
**/
select b.Name as Department, e2.Name as Employee, e2.Salary
from
Department b join
(
select DepartmentId, Name, Salary, dense_rank() over(partition by DepartmentId order by Salary desc) as rankId
from Employee
) as e2
on e2.DepartmentId = b.Id
where e2.rankId <= 3;
Either Excellent or Rusty