【问题标题】:How to create a query with all of dependencies in hierarchical organization?如何在分层组织中创建具有所有依赖项的查询?
【发布时间】:2019-11-27 07:29:49
【问题描述】:

我一直在努力创建一个查询来查看分层组织中的所有依赖项。但我唯一需要的是检索父依赖项。我附上了一张图片来展示我需要的东西。

感谢您提供任何线索。

这是我在生产表中尝试过的代码。

WITH CTE AS
    (SELECT
        H1.systemuserid,
        H1.pes_aprobadorid,
        H1.yomifullname,
        H1.internalemailaddress
    FROM [dbo].[ext_systemuser] H1
    WHERE H1.pes_aprobadorid is null
    UNION ALL 
    SELECT
        H2.systemuserid,
        H2.pes_aprobadorid,
        H2.yomifullname,
        H2.internalemailaddress           
    FROM [dbo].[ext_systemuser] H2
    INNER JOIN CTE c ON h2.pes_aprobadorid=c.systemuserid)
SELECT *
FROM CTE 
OPTION (MAXRECURSION 1000)

【问题讨论】:

    标签: sql tree recursive-query hierarchical


    【解决方案1】:

    您的查询就快到了。您只需将所有行作为起点。 join 也应该是 cte.parent_id = ext.user_id 而不是相反。我已经在postgres 中完成了一个示例查询,但您应该很容易将其适应您的 DBMS。

    with recursive st_units as (
      select 0 as id, NULL as pid, 'Director' as nm
      union all select 1, 0, 'Department 1'
      union all select 2, 0, 'Department 2'
      union all select 3, 1, 'Unit 1'
      union all select 4, 3, 'Unit 1.1'
    ),
    cte AS
    (
    SELECT id, pid, cast(nm as text) as path, 1 as lvl
    FROM st_units
    
    UNION ALL
    SELECT c.id, u.pid, cast(path || '->' || u.nm as text), lvl + 1
    FROM st_units as u
      INNER JOIN cte as c on c.pid = u.id
    )
    SELECT id, pid, path, lvl
    FROM cte
    ORDER BY lvl, id
    
    编号 |进程号 |路径 |等级 -: | ---: | :---------------------------------------------------- | --: 0 | |导演 | 1 1 | 0 |部门 1 | 1 2 | 0 |部门 2 | 1 3 | 1 |单元 1 | 1 4 | 3 |单元 1.1 | 1 1 | |部门1->主任| 2 2 | |部门2->主任| 2 3 | 0 |单元1->部门1 | 2 4 | 1 |单元 1.1->单元 1 | 2 3 | |单元1->部门1->主任| 3 4 | 0 |单元 1.1->单元 1->部门 1 | 3 4 | |单元1.1->单元1->部门1->主任| 4

    db小提琴here

    【讨论】:

      【解决方案2】:

      我已经找到了它正在工作的代码,但是当我包含一个超过 1800 的层次结构表时,查询是无止境的。

      With cte AS
      (select systemuserid, systemuserid as pes_aprobadorid, internalemailaddress, yomifullname
      from @TestTable
      union all
      SELECT c.systemuserid, u.pes_aprobadorid, u.internalemailaddress, u.yomifullname
      FROM @TestTable as u
      INNER JOIN cte as c on c.pes_aprobadorid = u.systemuserid
      )
      select distinct * from cte
      where pes_aprobadorid is not null
      OPTION (MAXRECURSION 0) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-06
        • 2022-10-30
        • 2013-07-13
        相关资源
        最近更新 更多