MySql 前3高工资
问题说明:
查询各部门工资前三高的所有员工信息
Employee 表包含所有员工信息,每个员工有其对应的工号 Id,姓名 Name,工资 Salary 和部门编号 DepartmentId 。
±—±------±-------±-------------+
| Id | Name | Salary | DepartmentId |
±—±------±-------±-------------+
| 1 | Joe | 85000 | 1 |
| 2 | Henry | 80000 | 2 |
| 3 | Sam | 60000 | 2 |
| 4 | Max | 90000 | 1 |
| 5 | Janet | 69000 | 1 |
| 6 | Randy | 85000 | 1 |
| 7 | Will | 70000 | 1 |
±—±------±-------±-------------+
Department 表包含公司所有部门的信息。
±—±---------+
| Id | Name |
±—±---------+
| 1 | IT |
| 2 | Sales |
±—±---------+
解决:
select
d.Name as Department,e1.Name as Employee,e1.Salary
from
Employee e1
join left Department d on e1.DepartmentId = d.Id
where
3 > (
select
count(distinct e2.Salary)
from
Employee e2 where e2.Salary > e1.Salary
and e1.DepartmentId = e2.DepartmentId
)
解题思路:
查询第N高的工资,就有N-1个工资(去除重复工资)大于当前工资,利用子查询查出大于当前工资的工资个数:
select
count(distinct e2.Salary)
from
Employee e2 where e2.Salary > e1.Salary
distinct 去除重复工资,e1.Salary当前工资;
再添加部门条件,e1.DepartmentId当前工资部门,查询部门大于当前工资的工资个数:
and e1.DepartmentId = e2.DepartmentId
查询前三高工资,子查询返回0,1,2分别对应第一、二、三高工资,where条件3 > (子查询),再join连表查询结果。
总结:
问题点在于如何查询第N高工资,而第N高工资有N-1个工资(去重)大于第N高工资,利用子查询查出大于当前工资的工资个数,再添加部门条件查询各部门第N高工资。
题目来源:
https://leetcode-cn.com/problems/department-top-three-salaries