查询层次结构中父级以下几级

时间:2019-05-09 05:07:15

标签: sql postgresql recursion

我正在处理员工数据,我认为我需要编写一个递归查询,但是对它们只有一点点熟悉。我正在努力寻找如何编写查询来确定经理以下级别的信息。

数据如下:

    | 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个以下的级别

关于如何编写此内容的任何想法/提示?预先感谢!

1 个答案:

答案 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中的一个示例。