Leetcode_数据库刷题_570. 至少有5名直接下属的经理

570题. 至少有5名直接下属的经理
SQL架构:

Create table If Not Exists Employee (Id int, Name varchar(255), Department varchar(255), ManagerId int)
Truncate table Employee
insert into Employee (Id, Name, Department, ManagerId) values ('101', 'John', 'A', 'None')
insert into Employee (Id, Name, Department, ManagerId) values ('102', 'Dan', 'A', '101')
insert into Employee (Id, Name, Department, ManagerId) values ('103', 'James', 'A', '101')
insert into Employee (Id, Name, Department, ManagerId) values ('104', 'Amy', 'A', '101')
insert into Employee (Id, Name, Department, ManagerId) values ('105', 'Anne', 'A', '101')
insert into Employee (Id, Name, Department, ManagerId) values ('106', 'Ron', 'B', '101')

Employee 表包含所有员工和他们的经理。每个员工都有一个 Id,并且还有一列是经理的 Id。

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

问题:给定 Employee 表,请编写一个SQL查询来查找至少有5名直接下属的经理。对于上表,您的SQL查询应该返回:

Name
John

解答

select a1.Name from  Employee a1,(
    select ManagerId from Employee 
    group by ManagerId 
    having count(*) >= 5
) a2
where a1.Id = a2.ManagerId;

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/managers-with-at-least-5-direct-reports

你可能感兴趣的:(Leetcode_数据库刷题,sql)