父子层次结构返回具有相应主ID的所有后代

时间:2017-07-23 20:05:07

标签: sql sql-server tsql sql-server-2016

我有一个父子层次结构表。我正在尝试返回每个子ID的所有子ID的列表。我的表定义如下:

UINavigationController

我所追求的结果如下:

CREATE TABLE Organization_Hierarchy_Test (ORGANIZATION_ID INT, PARENT_ORG_ID INT);
INSERT INTO Organization_Hierarchy_Test (ORGANIZATION_ID, PARENT_ORG_ID)
VALUES(1,0), (2,1), (3,1), (4,2), (5,2), (6,2), (7,3), (8,3), (9,3), (10,3);

我写的查询为我提供了每个+-----------------+---------------+--------------------------+ | ORGANIZATION_ID | PARENT_ORG_ID | ORIGINAL_ORGANIZATION_ID | +-----------------+---------------+--------------------------+ | 1 | 0 | 1 | | 2 | 1 | 1 | | 3 | 1 | 1 | | 4 | 2 | 1 | | 5 | 2 | 1 | | 6 | 2 | 1 | | 7 | 3 | 1 | | 8 | 3 | 1 | | 9 | 3 | 1 | | 10 | 3 | 1 | | 2 | 0 | 2 | | 3 | 0 | 2 | | 4 | 1 | 2 | | 5 | 1 | 2 | | 6 | 1 | 2 | | 7 | 1 | 2 | | 8 | 1 | 2 | | 9 | 1 | 2 | | 10 | 1 | 2 | | 4 | 0 | 4 | | 5 | 0 | 4 | | 6 | 0 | 4 | | 7 | 0 | 4 | | 8 | 0 | 4 | | 9 | 0 | 4 | | 10 | 0 | 4 | +-----------------+---------------+--------------------------+ 的所有后代的列表,但是我无法弄清楚如何返回实际上与所有organization_id相关的organization_id子孙后代。

我尝试添加group by并返回max ID但运气不佳。我明天有交货日期,我担心我无法及时完成这项工作。

with descendants as
  ( select PARENT_ORG_ID, ORGANIZATION_ID, 1 as level
    from Organization_Hierarchy_Test OH
  union all
    select d.PARENT_ORG_ID ,  OH1.ORGANIZATION_ID, d.level + 1
    from descendants as d
      join Organization_Hierarchy_Test OH1 on d.ORGANIZATION_ID = OH1.PARENT_ORG_ID
  ) 
select ORGANIZATION_ID, PARENT_ORG_ID, level
from descendants 
order by level, PARENT_ORG_ID,  ORGANIZATION_ID

有关如何将原始Organization_ID与所有后代organization_id一起退回的任何想法?

我正在尝试将其推送到表格模型,这将节省我处理数据的大量时间。

非常感谢。

1 个答案:

答案 0 :(得分:0)

将您的CTE更改为只包含一个额外的列d.ORGANIZATION_ID AS Orig

with descendants as
  ( select PARENT_ORG_ID, ORGANIZATION_ID, ORGANIZATION_ID AS Orig, 1 as level
    from Organization_Hierarchy_Test OH
  union all
    select d.PARENT_ORG_ID ,  OH1.ORGANIZATION_ID, d.ORGANIZATION_ID AS Orig, d.level + 1
    from descendants as d
      join Organization_Hierarchy_Test OH1 on d.ORGANIZATION_ID = OH1.PARENT_ORG_ID
  )