leetcode 184. 部门工资最高的员工
作者:互联网
1 题目描述
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 |
±-----------±---------±-------+
2 解题
下面的解法中,第一种是笔者自己写的,第二种是参考的大牛的方案。经典解法果然还是简洁的多呀!
注意:第二种解法中 in的 用法。同时判断两个字段是否出现在一条记录中,漂亮!
# 法1
select Department.Name as Department,Employee.Name as Employee,Employee.Salary
from(
select Id,rankInDepart
from (
select Id ,if(@preDepartId = DepartmentId , if(Salary = @preSalary,@r,@r := @r + 1),@r := 1) as rankInDepart,@preDepartId := DepartmentId,@preSalary := Salary
from Employee,(select @r := 0,@preDepartId := null,@preSalary := 0) t1
order by DepartmentId,Salary desc
) t2 where rankInDepart = 1
) t3
join Employee on t3.Id = Employee.Id
join Department on Employee.DepartmentId = Department.Id
#2 法2
select Department.Name as Department,Employee.Name as Employee,Salary
from Employee join Department on Employee.DepartmentId = Department.Id
where (DepartmentId ,Salary) in(
select DepartmentId,max(Salary)
from Employee
group by DepartmentId
)
标签:Salary,leetcode,Department,DepartmentId,184,Employee,员工,Id,select 来源: https://blog.csdn.net/ZZh1301051836/article/details/100015204