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. Or please tell me if there are better options. Thank you.
2
Answers
You could try something like this:
I hope the syntax is correct and works…
Here how to do it using the recursive CTE :
The nonrecursive SELECT produces the row for the top level managers (the row with a NULL managerId).
Each row produced by the recursive SELECT finds all employees who report directly to an employee produced by a previous row
Recursion ends when employees have no others who report to them.
Demo here