Reputation: 101
I am working with employee data and I think I need to write a recursive query, but I'm only a little familiar with them. I'm struggling to find out how to write a query that identifies how many levels are below a manager.
The data looks like this:
| employee | manager |
|-------------+------------+
| employee1 | employee1 |
| employee2 | employee1 |
| employee3 | employee1 |
| employee3 | employee2 |
| employee4 | employee1 |
| employee4 | employee2 |
| employee4 | employee3 |
| employee5 | employee1 |
| employee6 | employee1 |
| employee6 | employee2 |
...
Essentially this portion is telling me:
employee1
has 2 levels below, because they manage employee2, who manages employee3.employee2
has 1 levels belowemployee3
has 1 levels belowemployee4
has 0 levels belowemployee5
has 0 levels belowemployee6
has 0 levels belowAny ideas/tips on how to write this? Thanks in advance!
Upvotes: 0
Views: 116
Reputation: 1269703
You can use a recursive CTE:
with recursive cte as (
select employee, employee as s, 0 as lev
from t
union all
select cte.employee, t.employee, lev + 1
from cte join
t
on t.manager = cte.s and t.manager <> t.employee
)
select distinct on (employee) employee, lev
from cte
order by employee, lev desc;
Here is an example in db<>fiddle.
Upvotes: 3