LeetCode:184.部门工资最高的员工
题目链接:https://leetcode-cn.com/problems/department-highest-salary/
题目
Employee
表包含所有员工信息,每个员工有其对应的 Id, salary 和 department Id。
+----+-------+--------+--------------+
| Id | Name | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1 | Joe | 70000 | 1 |
| 2 | Henry | 80000 | 2 |
| 3 | Sam | 60000 | 2 |
| 4 | Max | 90000 | 1 |
+----+-------+--------+--------------+
Department 表包含公司所有部门的信息。
+----+----------+
| Id | Name |
+----+----------+
| 1 | IT |
| 2 | Sales |
+----+----------+
编写一个 SQL 查询,找出每个部门工资最高的员工。例如,根据上述给定的表格,Max 在 IT 部门有最高工资,Henry 在 Sales 部门有最高工资。
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Max | 90000 |
| Sales | Henry | 80000 |
+------------+----------+--------+
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/department-highest-salary
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答
哈哈,第一次调试调试就通过。
---- oracle ----
/* Write your PL/SQL query statement below */
select b.Name as Department,
t.Name as Employee,
t.Salary as Salary
from Department b
left join
(
select Name,
Salary,
DepartmentId,
rank() over(partition by DepartmentId order by Salary desc) as rank
from Employee
) t
on t.DepartmentId = b.Id
where t.rank = 1; ---- 791ms
通过观察测试样例的通过情况,发现自己代码的问题。
一开始使用 row_number()
进行排序的时候,发现同一个薪水会得到不同的排名,不符合题目的要求,因此改为 rank()
则通过。
第一次不通过的时候,发现测试案例存在 Department
表存在为空的情况,所以把 left join
的2个表交换位置,便可以。
使用 join
和 in
进行解答。
---- MySQL ----
select b.name as Department,
a.name as Employee,
Salary
from Employee a
join Department b
on a.DepartmentId = b.Id
where (a.DepartmentId, Salary) in
(
select DepartmentId,
max(Salary) as Salary
from Employee
group by DepartmentId
); ---- 221ms
使用 left join
时同样报错,因为有一个样例没通过,改为 join
或者直接使用 inner join
便可以。
思考
一步步思考,思考,思考最重要!
MySQL
中 in
可以2个字段一起。
select xxx
from yyy
where (a, b) in (c, d);
总结来看,还是我一开始使用的 rank()
函数最优美,哈哈!
后续再总结一下 oracle
中4个排序函数的使用情况。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)