我有一个3 SQL表,其中包含树节点和树叶以及节点描述 我想以以下格式打印数据
Parent6 Parent5 Parent4 Parent3 Parent1 Child Description
A1
B1
C1
D1A - Child 1
D1B - Child 2
C2
D2A - Child 3
D2B - Child 4
B2
我在节点表中有TreeNodeNuM,TreeName,级别
答案 0 :(得分:0)
我为类似的事情编写了这段代码,通常我只使用LongID和LongDescription列满足我的需要,我添加了一些案例以使输出类似于您的示例,请注意,对于我的层次结构,该级别从0开始>
WITH cte AS
(
SELECT CAST(RIGHT('000' + CAST(HierarchyID AS VARCHAR),3) AS VARCHAR(100)) as M,
CAST(Description AS VARCHAR(MAX)) AS LongID, *
FROM HIERARCHY
WHERE Level = 0
UNION ALL
SELECT CAST(cte.M + '_' + RIGHT('000' + CAST(si.HierarchyID AS varchar), 3) AS VARCHAR(100)),
CAST(cte.LongID + '->' + si.Description AS VARCHAR(MAX)),
si.*
FROM HIERARCHY si
INNER JOIN cte
ON si.ParentHierarchyID = cte.HierarchyID
)
SELECT
CASE WHEN Level = 0 THEN Description ELSE '' END AS Parent6,
CASE WHEN Level = 1 THEN Description ELSE '' END AS Parent5,
CASE WHEN Level = 2 THEN Description ELSE '' END AS Parent4,
CASE WHEN Level = 3 THEN Description ELSE '' END AS Parent3,
CASE WHEN Level = 4 THEN Description ELSE '' END AS Parent1,
CASE WHEN Level = 5 THEN Description ELSE '' END AS Child,
FROM cte
ORDER BY LongID