I have a table employees
as below:
id | name | managerId |
---|---|---|
1 | Annie | Null |
2 | Bob | Null |
3 | Chloe | 1 |
4 | Danny | 2 |
5 | Eddie | 3 |
6 | Felicia | 3 |
7 | Georgia | 4 |
8 | Harper | 3 |
Top-level management is Annie and Bob as they don’t have managers above them (managerId
is Null). I need to count the number of employees top-level managers are in charge. The expected output:
id | name | number of employees |
---|---|---|
1 | Annie | 4 |
2 | Bob | 2 |
Annie is the direct manager of Chloe, and Chloe is the direct manager of Eddie, Felicia and Harper, so the number returned is 4.
As far as I read, it seems I could try recursive query but I still don’t know how to do. Please help. Thank you.
1
You could try something like this:
I hope the syntax is correct and works…
with cte_managers as
(
Select managerId,
count(*) as NoOfEmployees
From employees
Where managerId is not null
Group By managerId
)
Select e.id,
e.name,
a.NoOfEmployees
from employees e
inner join cte_managers as a on a.managerId= e.id
where e.managerId is null
order by e.name
1