Managers With At Least 5 Direct Reports Problem
Description
LeetCode Problem 570.
The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager 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 |
+------+----------+-----------+----------+
Given the Employee table, write a SQL query that finds out managers with at least 5 direct report. For the above table, your SQL query should return:
+-------+
| Name |
+-------+
| John |
+-------+
Solution
Approach: Count Reports per Manager, Then Join
An employee's direct reports are the rows whose ManagerId is that employee's Id. So:
- Group
EmployeebyManagerIdand keep the groups withCOUNT(*) >= 5. This gives the ids of managers with at least five direct reports. - Join those ids back to
EmployeeonIdto get the managers' names.
Grouping by the id and joining afterwards, rather than grouping by name, keeps two different managers who share a name apart. The top-level employees have ManagerId NULL; they form their own group, but NULL = Id never matches, so that group can't produce a row.
In the test data Ron has four direct reports, one short of five, so only John (five reports) is returned.
The Pandas version counts rows per ManagerId with groupby(...).size() and keeps the employees whose Id is among the managers with at least five.
SELECT m.Name
FROM Employee AS m
JOIN (
SELECT ManagerId
FROM Employee
GROUP BY ManagerId
HAVING COUNT(*) >= 5
) AS r
ON r.ManagerId = m.Id;