570. 至少有5名直接下属的经理 - 力扣(LeetCode)
题目
表: Employee
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| name | varchar |
| department | varchar |
| managerId | int |
+-------------+---------+
id 是此表的主键(具有唯一值的列)。
该表的每一行表示雇员的名字、他们的部门和他们的经理的id。
如果managerId为空,则该员工没有经理。
没有员工会成为自己的管理者。
编写一个解决方案,找出至少有五个直接下属的经理。
以 任意顺序 返回结果表。
查询结果格式如下所示。
示例 1:
输入:
Employee 表:
+-----+-------+------------+-----------+
| id | name | department | managerId |
+-----+-------+------------+-----------+
| 101 | John | A | Null |
| 102 | Dan | A | 101 |
| 103 | James | A | 101 |
| 104 | Amy | A | 101 |
| 105 | Anne | A | 101 |
| 106 | Ron | B | 101 |
+-----+-------+------------+-----------+
输出:
+------+
| name |
+------+
| John |
+------+
思路
- 先将Employee表和自身根据id和managerId是否相等做连接,然后选择数据大于等于5的那个人的name。
官方题解(思路是会,但是语句不会,只能好好学了)
- 先学语句:
- 对分组条件进行筛选:在分组语句后加 having 条件——这样选择的条件就可以单独计算了。
- 选择出来的内容也可以成为一张新的表作为子表继续被选择,需要被小括号包住(最好给个名字,其中的新字段也要记得更名)。
- 接下来看看官解给的几个思路:
- 思路一:将连接结果作为一个新表,再在新表上做判断。
- 复现:
# Write your MySQL query statement below select name from ( select e.name, count(e.id) as employeeCount from Employee as e join Employee as m on e.id = m.managerId group by e.id ) as Managers where Managers.employeeCount >= 5
思路二:利用having语句对组合完的数据做条件筛选。
复现:
# Write your MySQL query statement below select e.name from Employee as e join Employee as m on e.id = m.managerId group by e.id having count(e.id) >= 5
思路三(开销最小):直接将Employee表根据managerId做group by,挑选managerId作为新表的id然后与Employee在做连接,输出姓名即可。
复现:
# Write your MySQL query statement below select name from ( select managerId as Id from Employee group by managerId having count(managerId) >= 5 ) as Managers join Employee where Managers.Id = Employee.id