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;
posted @   Garrett_Wale  阅读(104)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示