LeetCode SQL #570. Managers with at Least 5 Direct Reports

Medium Problem

Pragya Verma
2 min readSep 24, 2022
Photo by Martin Shreder on Unsplash

Table: Employee

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| name | varchar |
| department | varchar |
| managerId | int |
+-------------+---------+
id is the primary key column for this table.
Each row of this table indicates the name of an employee, their department, and the id of their manager.
If managerId is null, then the employee does not have a manager.
No employee will be the manager of themself.

Write an SQL query to report the managers with at least five direct reports.

Return the result table in any order.

Example :

Input: 
Employee table:
+-----+-------+------------+-----------+
| id | name | department | managerId |
+-----+-------+------------+-----------+
| 101 | John | A | None |
| 102 | Dan | A | 101 |
| 103 | James | A | 101 |
| 104 | Amy | A | 101 |
| 105 | Anne | A | 101 |
| 106 | Ron | B | 101 |
+-----+-------+------------+-----------+
Output:
+------+
| name |
+------+
| John |
+------+

I solved this problem using CTEs in SQL. In the CTE I get the subtable that I need as per the condition and then query this subtable to get the desired result.

The common table expression (CTE) is a powerful construct in SQL that helps simplify a query. CTEs work as virtual tables (with records and columns), created during the execution of a query, used by the query, and eliminated after query execution.

So first I am fetching a part of the table using CTE that gives me the Id of managers who have a minimum of 5 employees under them.

SELECT managerId
FROM Employee
Group by managerId
HAVING count(id) >= 5

Then I query the above virtual table to get the name of the manager by mapping the managerId from the above table to the Employees table.

The overall solution looks like this —

WITH report_count AS(
SELECT managerId
FROM Employee
Group by managerId
HAVING count(id) >= 5
)
SELECT name
FROM Employee
WHERE id IN (SELECT managerId FROM report_count)

--

--

Pragya Verma
Pragya Verma

Written by Pragya Verma

Data professional focused on end-to-end solutions, exploring data analytics and engineering to unlock data’s potential.

No responses yet