列出数据透视表中每个级别的特定节点的所有祖先或父节点,该数据透视表包含级别作为SQL Server中的属性

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

我有一个表'temp',它的ID和它的直接父ID为列。下表如下:

temp table

                              1
                            /   \
                           2     3
                          /|\     \
                         4 5 6     7
                        /
                       8

节点的层次结构可以用上面的树结构表示。

现在,我要使用具有级别(如Level1,Level2等)作为属性的recursive cte列出透视表中所有级别上存在的每个节点的所有祖先节点或父节点。为了获得此输出,我计算了非数据透视表中的所有父节点,每个节点相对于其父节点的级别。如下的sql查询:

WITH ctetable as 
(
    SELECT S.id, S.parent, 1 as level
    FROM temp as S where S.parent is not null
    UNION ALL
    SELECT S2.id, p.parent, p.level + 1
    FROM ctetable AS p JOIN temp as S2 on S2.parent = p.id
)
SELECT * FROM ctetable ORDER BY id;

以上查询的输出如下所示:

cte output

但是,我想透视包含特定节点每个级别下的父ID的递归cte。说,对于id = 4,它应该分别在Level3,Level2和Level1下显示父ID 4、2和1。为此,我编写了以下查询:

WITH ctetable as 
(
    SELECT S.id, S.parent, 1 as level
    FROM temp as S where S.parent is not null
    UNION ALL
    SELECT S2.id, p.parent, p.level + 1
    FROM ctetable AS p JOIN temp as S2 on S2.parent = p.id
)

SELECT      
            myid,
            [pn].[1] AS [Level1],
            [pn].[2] AS [Level2],
            [pn].[3] AS [Level3] 
FROM
     (
         SELECT [a].id,
                [a].id as myid,
                [a].level
         FROM ctetable AS [a]
     ) AS [hn] PIVOT(max([hn].id) FOR [hn].level IN([1],[2],[3])) AS [pn]

但是,输出表不是所需的表,因为它包含与特定节点的每个级别下的父代ID重复的相同ID,相反,它应该包含该节点在各个级别下的所有父代。我执行上述查询后得到的输出如下所示:

main output

有人可以帮我这个忙吗?...

sql-server tsql pivot hierarchy recursive-cte
1个回答
0
投票

如果您的水平已知或最大,并且假设我没有扭转您想要的结果。

最好以文本形式而不是以图像形式发布样本数据和所需结果

示例

Declare @YourTable Table ([id] int,[parent] int)
Insert Into @YourTable Values 
 (1,null)
,(2,1)
,(3,1)
,(7,3)
,(4,2)
,(5,2)
,(6,2)
,(8,4)

;with cteP as (
      Select id
            ,Parent 
            ,PathID = cast(id as varchar(500))
      From   @YourTable
      Where  Parent is Null
      Union  All
      Select id  = r.id
            ,Parent  = r.Parent 
            ,PathID = cast(concat(p.PathID,',',r.id) as varchar(500))   -- Perhaps I reversed the desired sequence
      From   @YourTable r
      Join   cteP p on r.Parent  = p.id)
Select ID
      ,B.*
 From  cteP A
 Cross Apply (
                Select Level1 = xDim.value('/x[1]','int')
                      ,Level2 = xDim.value('/x[2]','int')
                      ,Level3 = xDim.value('/x[3]','int')
                      ,Level4 = xDim.value('/x[4]','int')
                      ,Level5 = xDim.value('/x[5]','int')
                From  (Select Cast('<x>' + replace(PathID,',','</x><x>')+'</x>' as xml) as xDim) as X 
             ) B
  Order By PathID

返回

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.