185. 部门工资前三高的所有员工

派生表+dense_rank+JOIN

https://leetcode.cn/problems/department-top-three-salaries/

一开始下意识用的LEFT JOIN,但发现第18个样例过不去。

发现多了null。因为LEFT JOIN如果找不到记录就会在被LEFT JOIN的记录旁边加上null,也就是”LEFT产null“。那把LEFT JOIN改成JOIN或者去掉LEFT就完事了。再跑一遍看看。

dense_rank也只能派生表用了,外面用的话会多一列排序。不过不用窗口函数的话,估计是GROUP BY+ORDER BY。

SQL
# Write your MySQL query statement below
SELECT A.Department,A.Employee,A.Salary
FROM(
    SELECT Department.name AS Department,Employee.name AS Employee,Employee.salary AS Salary,
    dense_rank()over(partition by Employee.departmentId ORDER BY Employee.salary DESC) as rk
    FROM Department
    JOIN Employee 
    ON Department.id=Employee.departmentId
)AS A 
WHERE A.rk<=3

Subscribe
提醒
0 评论
Inline Feedbacks
View all comments
0
在此留下你的评论x