LeetCode:MySQL分组内取前几名问题(难度:困难)

题目:查询部门工资前三高的所有员工

Employee 表包含所有员工信息,每个员工有其对应的工号 Id,姓名 Name,工资 Salary 和部门编号 DepartmentId 。
在这里插入图片描述
Department 表包含公司所有部门的信息。
在这里插入图片描述
编写一个 SQL 查询,找出每个部门获得前三高工资的所有员工。例如,根据上述给定的表,查询结果应返回:
在这里插入图片描述
解释:IT 部门中,Max 获得了最高的工资,Randy 和 Joe 都拿到了第二高的工资,Will 的工资排第三。销售部门(Sales)只有两名员工,Henry 的工资最高,Sam 的工资排第二。

题解

对于这种分组内取前几名的问题,可以先group by然后用having count()来筛选。思路为:
先找到每个部门工资前三的员工ID(自联结+group by+having)
再找到每个部门工资前三的部门名称、员工名称、工资和员工ID(两表联结)
最后子查询嵌套即可

1.找到每个部门工资前三的员工ID

用Employee和自己做连接,连接条件是【部门相同但工资比我高
接下来按照having count(Salary) <= 2来筛选的原理是:如果【跟我一个部门而且工资比我高的人数】不超过2个,那么我一定是部门工资前三
这样就可以查询出每个部门工资前三的员工ID

select e1.id,e1.name,e1.DepartmentId
from employee e1 left join employee e2 
     on e1.DepartmentId=e2.DepartmentId and e1.Salary<e2.Salary
group by e1.id
having count(distinct e2.Salary)<=2;

2.外层嵌套:找到每个部门工资前三的部门名称、员工名称、工资和员工ID

select d.Name as Department,e.Name as Employee,e.Salary as Salary
from Employee as e left join Department as d 
on e.DepartmentId = d.Id
where e.Id in(#每个部门工资前三的员工ID)
and e.DepartmentId in (select Id from Department)
order by d.Id asc,e.Salary desc;

进行1和2的子查询嵌套即可得到

完整代码如下:

select d.Name as Department,e.Name as Employee,e.Salary as Salary
from Employee as e left join Department as d 
on e.DepartmentId = d.Id
where e.Id in
(
    select e1.Id
    from Employee as e1 left join Employee as e2
    on e1.DepartmentId = e2.DepartmentId and e1.Salary < e2.Salary
    group by e1.Id
    having count(distinct e2.Salary) <= 2
)
and e.DepartmentId in (select Id from Department)
order by d.Id asc,e.Salary desc
发布了63 篇原创文章 · 获赞 56 · 访问量 6465

猜你喜欢

转载自blog.csdn.net/weixin_43412569/article/details/104937138