我正在处理员工数据,我认为我需要编写一个递归查询,但是对它们只有一点点熟悉。我正在努力寻找如何编写查询来确定经理以下级别的信息。
数据如下:
| employee | manager |
|-------------+------------+
| employee1 | employee1 |
| employee2 | employee1 |
| employee3 | employee1 |
| employee3 | employee2 |
| employee4 | employee1 |
| employee4 | employee2 |
| employee4 | employee3 |
| employee5 | employee1 |
| employee6 | employee1 |
| employee6 | employee2 |
...
基本上这部分告诉我:
employee1
下有2个级别,因为它们管理的是employee2,而后者又管理着employee3。employee2
有1个以下的级别employee3
有1个以下的级别employee4
有0个以下的级别employee5
有0个以下的级别employee6
有0个以下的级别关于如何编写此内容的任何想法/提示?预先感谢!
答案 0 :(得分:3)
您可以使用递归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是db <> fiddle中的一个示例。