具有非唯一ID的分层查询

时间:2018-11-08 21:03:39

标签: sql sql-server tsql hierarchical-data

我正在尝试创建一个查询,以将层次结构表结构转换为列。

每个节点都有一个父级。但是 Node 不是唯一的数字。在每个根叶中都是唯一的。但可以存在于另一个父项下。

我尝试过CTE。并具有多个SELECT .. UNION ...

但是我无法过滤掉它在同一个根叶中。 例如,我将两个父级01的两条选定行都设为09。

最大深度为4。

我想要的结果是。 RUBRICCODE; NAME0; NAME1; NAME2; NAME3; NAME4 0100000000;财务管理文件;;; 0100100000;金融管理文档;患者管理; ...

select * from (

  select t0.RUBRICCODE, t0.PATH, t0.NAME Rubr0, '' Rubr1, '' Rubr2, '' Rubr3, '' Rubr4
  from dacs_treestructure t0
  where t0.DEPTH = 0

  UNION ALL

  select t1.RUBRICCODE, t1.PATH, t0.NAME Rubr0, t1.NAME Rubr1, '' Rubr2, '' Rubr3, '' Rubr4
  from dacs_treestructure t0
  join dacs_treestructure t1 on t0.NODE = t1.PARENT
  where t0.DEPTH = 0 and t1.DEPTH = 1

  UNION ALL

  select t2.RUBRICCODE, t2.PATH, t0.NAME Rubr0, t1.NAME Rubr1, t2.NAME Rubr2, '' Rubr3, '' Rubr4
  from dacs_treestructure t0
  join dacs_treestructure t1 on t0.NODE = t1.PARENT
  join dacs_treestructure t2 on t1.NODE = t2.PARENT
  where t0.DEPTH = 0 and t1.DEPTH = 1 and t2.DEPTH = 2

) x order by 1

enter image description here

查询结果。所选行来自父级09。并且不应该存在。

enter image description here

1 个答案:

答案 0 :(得分:1)

我设法使用已经存在的列 PATH 解决了我的问题。 通过将正斜杠替换为XML结构,我设法将不同的部分作为列。 然后,我再次按级别加入源表以获取该级别的描述。

WITH Split_Tree (RUBRICCODE,XmlPath)
AS
(
    SELECT
         RUBRICCODE
        ,CONVERT(XML,'<Paths><Path>' + REPLACE(PATH,'/', '</Path><Path>') + '</Path></Paths>') AS XmlPath
     FROM dacs_treestructure
)
SELECT t.RUBRICCODE, t0.NAME NAME0, t1.NAME NAME1, t2.NAME NAME2, t3.NAME NAME3, t4.NAME NAME4
FROM (
SELECT
     RUBRICCODE
    ,XmlPath.value('/Paths[1]/Path[1]','varchar(15)') AS PATH0
    ,XmlPath.value('/Paths[1]/Path[2]','varchar(15)') AS PATH1
    ,XmlPath.value('/Paths[1]/Path[3]','varchar(15)') AS PATH2
    ,XmlPath.value('/Paths[1]/Path[4]','varchar(15)') AS PATH3
    ,XmlPath.value('/Paths[1]/Path[5]','varchar(15)') AS PATH4
FROM Split_Tree) t
LEFT JOIN dacs_treestructure t0 on t0.DEPTH = 0 AND t0.PATH = (PATH0)
LEFT JOIN dacs_treestructure t1 on t1.DEPTH = 1 AND t1.PATH = (PATH0 + '/' + PATH1)
LEFT JOIN dacs_treestructure t2 on t2.DEPTH = 2 AND t2.PATH = (PATH0 + '/' + PATH1 + '/' + PATH2)
LEFT JOIN dacs_treestructure t3 on t3.DEPTH = 3 AND t3.PATH = (PATH0 + '/' + PATH1 + '/' + PATH2 + '/' + PATH3)
LEFT JOIN dacs_treestructure t4 on t4.DEPTH = 4 AND t4.PATH = (PATH0 + '/' + PATH1 + '/' + PATH2 + '/' + PATH3 + '/' + PATH4)
GO