如何从Postgres表中列出管理级别

问题描述 投票:0回答:1

我有一个包含以下字段的表:ID,manager_id和候选人名称

manager_id将指向id,这使我可以引用管理链。我想生成如下输出:

id |候选人名称| manager_id | lvl1 mgrID | lvl1 mgr候选人姓名| lvl2 mgrID | lvl2 mgr候选人姓名|等等...

我最终希望构建这种结构的csv,以便在报表中利用它。

到目前为止,我已经使用以下查询来接近此内容:

CREATE EXTENSION tablefunc;

SELECT * FROM connectby('job', 'id', 'manager_id', '261', 0, ',') AS t(id int, manager_id int, level int, ord text) order by id;

输出以下内容:

  id   | manager_id | level |                       ord                        
-------+------------+-------+--------------------------------------------------
     2 |         12 |     3 | 261,226,12,2
     3 |          2 |     4 | 261,226,12,2,3
     4 |        106 |     4 | 261,226,110,106,4
     5 |          4 |     5 | 261,226,110,106,4,5
     6 |         86 |     4 | 261,226,12,86,6
     7 |        920 |     6 | 261,226,12,86,6,920,7
     8 |         86 |     4 | 261,226,12,86,8
     9 |          8 |     5 | 261,226,12,86,8,9
    10 |        145 |     5 | 261,226,12,4209,145,10
    11 |        139 |     7 | 261,226,12,4209,145,10,139,11
    12 |        226 |     2 | 261,226,12
    13 |       4209 |     4 | 261,226,12,4209,13
    14 |        159 |     5 | 261,226,12,69,159,14
    15 |         14 |     6 | 261,226,12,69,159,14,15
    16 |        110 |     3 | 261,226,110,16

ord列为我提供了管理链,但是我在如何生成具有所需mgr级别的列方面遇到了麻烦。这也不必仅存在于SQL中。

请注意,管理水平可以深入到十几岁。感谢有关如何解决此问题的任何想法。

postgresql tree hierarchy
1个回答
0
投票

如果您事先知道层次结构中的最大级别数(例如3),则一个选项使用条件聚合:

with recursive cte as (
    select id employee_id, id, manager_id, candidate_name, 0 lvl from mytable
    union all
    select c.employee_id, t.id, t.manager_id, t.candidate_name, lvl + 1
    from cte c
    inner join mytable t on t.id = c.manager_id
)
select 
    employee_id,
    max(case when lvl = 1 then id             end) level1_manager_id,
    max(case when lvl = 1 then candidate_name end) level1_candidate_name,
    max(case when lvl = 2 then id             end) level2_manager_id,
    max(case when lvl = 2 then candidate_name end) level2_candidate_name
    max(case when lvl = 2 then id             end) level3_manager_id,
    max(case when lvl = 2 then candidate_name end) level3_candidate_name
from cte
group by employee_id
© www.soinside.com 2019 - 2024. All rights reserved.