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个表交换位置,便可以。

使用 joinin 进行解答。

---- 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 便可以。

思考

一步步思考,思考,思考最重要!

MySQLin 可以2个字段一起。

select xxx
from yyy
where (a, b) in (c, d);

总结来看,还是我一开始使用的 rank() 函数最优美,哈哈!

后续再总结一下 oracle 中4个排序函数的使用情况。

猜你喜欢

转载自www.cnblogs.com/hider/p/11746419.html