How Big Is Each Manager's Team?
Kestrel Labs is sizing a training programme for people who manage others, and needs to know how many managers there are and how many direct reports each of them carries.
The reporting line lives on the employee row: each person's row holds the id of the person they report to. Managers are therefore not marked anywhere — somebody is a manager exactly when other rows point at them. The people at the top of a line have nothing to point at, so their own slot holds NULL, and those employees are not part of this count in either direction: they are not reports, and being at the top does not by itself make somebody a manager.
employees — one row per employee. manager_id holds the id of that person's manager, or NULL for someone who reports to nobody.
| id | name | department_id | salary | hire_date | manager_id |
|---|---|---|---|---|---|
| 1 | Ava Chen | 1 | 145000 | 2021-03-14 | NULL |
| 2 | Ben Ortiz | 1 | 118000 | 2022-06-01 | 1 |
| 3 | Cara Novak | 1 | 121000 | 2023-01-10 | 1 |
| 4 | Deshawn Lee | 2 | 95000 | 2020-09-23 | NULL |
| 5 | Elin Kask | 2 | 88000 | 2022-11-05 | 4 |
| 6 | Farid Amiri | 3 | 76000 | 2023-04-18 | NULL |
| 7 | Grace Kim | 4 | 132000 | 2021-07-30 | NULL |
| 8 | Hugo Silva | 4 | 110000 | 2023-02-14 | 7 |
| 9 | Ines Duarte | 4 | 104000 | 2023-08-01 | 7 |
| 10 | Jonas Weber | 2 | 91000 | 2021-12-19 | 4 |
The table already exists in the database — there is nothing to create or load.
Task: Write a query returning two columns, manager_id and num_reports, with one row for each employee id that appears as somebody's manager, and how many people report to them. Employees with no manager recorded must not form a row of their own. Rows come back sorted by manager_id, smallest first.
Example output — shape only, on an invented company; both the ids and the counts are made up.
| manager_id | num_reports |
|---|---|
| 3 | 5 |
| 6 | 3 |
| 9 | 8 |
Sign in to solve this problem
Reading problems is free for everyone — solving them (Run, Submit, and tracking what you've solved) needs an account.
Sign in