力扣185. 部门工资前三高的所有员工
https://leetcode-cn.com/problems/department-top-three-salaries/
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 |
+----+----------+
编写一个 SQL 查询,找出每个部门获得前三高工资的所有员工。例如,根据上述给定的表,查询结果应返回:
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Max | 90000 |
| IT | Randy | 85000 |
| IT | Joe | 85000 |
| IT | Will | 70000 |
| Sales | Henry | 80000 |
| Sales | Sam | 60000 |
+------------+----------+--------+
解释:
IT 部门中,Max 获得了最高的工资,Randy 和 Joe 都拿到了第二高的工资,Will 的工资排第三。销售部门(Sales)只有两名员工,Henry 的工资最高,Sam 的工资排第二。
我的答案:
# Write your MySQL query statement below
#这道题题目有点问题,很容易会错意
select Department.Name as Department,a.Name as Employee,a.Salary
#两表连接,而且这种应该用join
#JOIN 是一个更常用也更有效的将表连起来的办法,我们使用 ON 来指明条件
from Employee a join Department on a.DepartmentId=Department.Id
where #where过滤掉超过3的员工
(
select count(distinct b.salary)#计算排名
from Employee b
#注意这里多了一条语句a.DepartmentId=b.DepartmentId用来起到分组分部门比较的作用
#where过滤完后,无法用group by分组,所以用a.DepartmentId=b.DepartmentId分组
where b.salary>=a.salary and a.DepartmentId=b.DepartmentId
)<=3
#按照题目参考来排序
order by Department,a.Salary desc;
和力扣178. 分数排名相同的是用到了一样的where子查询起到排序作用
https://blog.csdn.net/qq_35683407/article/details/105424473
select a.Score as Score,
(select count(distinct b.Score) from Scores b where b.Score >= a.Score) as Rank
from Scores a
order by a.Score DESC;
不同的是:
where #where过滤掉超过3的员工
(
select count(distinct b.salary)#计算排名
from Employee b
#注意这里多了一条语句a.DepartmentId=b.DepartmentId用来起到分组分部门比较的作用
#where过滤完后,无法用group by分组,所以用a.DepartmentId=b.DepartmentId分组
where b.salary>=a.salary and a.DepartmentId=b.DepartmentId
)<=3
#注意这里多了一条语句a.DepartmentId=b.DepartmentId用来起到分组分部门比较的作用
#where过滤完后,无法用group by分组,所以用a.DepartmentId=b.DepartmentId分组
这是困扰我最久的地方,一直想用group by分组解决,其实只要对应分组条件查询就行了
里面的where实现分组比较,外面的where实现“前三名”筛选