我有一个分类表,因为我正在创建父类别的父类别,
现在我正在获取这样的类别
Select CatID,CatName,ParentCatID from Category
CatID CatName ParentCatID
35 Test1 0
36 Test2 35
37 Test3 36
38 Test4 0
39 Test5 38
40 Test6 39
我想要这样的输出,
CatID CatName ParentCatID ParentRoot
35 Test1 0 None
36 Test2 35 Test1
37 Test3 36 Test1>Test2
38 Test4 0 None
39 Test5 38 Test4
40 Test6 39 Test4>Test5
答案 0 :(得分:1)
如果您具有未知数量的层次结构,则可以使用递归公用表表达式:
WITH CategoryCTE AS
( SELECT CatID,
CatName,
ParentCatID,
RecursionLevel = 1,
ParentRoot = CAST('None' AS VARCHAR(MAX)),
LastParentCatID = ParentCatID
FROM Category
UNION ALL
SELECT cte.CatID,
cte.CatName,
cte.ParentCatID,
cte.RecursionLevel + 1,
ParentRoot = CASE WHEN cte.RecursionLevel = 1 THEN '' ELSE cte.ParentRoot + '>' END + c.CatName,
LastParentCatID = c.ParentCatID
FROM CategoryCTE cte
INNER JOIN Category c
ON c.CatID = cte.LastParentCatID
), MaxRecursion AS
( SELECT CatID,
CatName,
ParentCatID,
ParentRoot,
RowNum = ROW_NUMBER() OVER(PARTITION BY CatID ORDER BY RecursionLevel DESC)
FROM CategoryCTE
)
SELECT CatID, CatName, ParentCatID, ParentRoot
FROM MaxRecursion
WHERE RowNum = 1;
<强> Example on SQL Fiddle 强>
答案 1 :(得分:0)
表中的级别数量是否有限制?如果您知道它永远不会超过2级,那么可以通过自联接来实现它:
SELECT
C.CatID,
C.CatName,
C.ParentCatID,
CASE
WHEN P.CatName is NULL THEN 'None'
ELSE WHEN GP.CatName is NULL THEN P.CatName
ELSE P.CatName + '>' + GP.CatName
END
FROM
Category C -- child
LEFT OUTER JOIN Category P ON C.ParentCatID = P.CatID -- parent
LEFT OUTER JOIN Category GP ON P.ParentCatID = GP.CatID -- grand parent
但是只有2级或更低级别才有效。除此之外,您应该考虑使用公用表表达式。