你很接近。您需要删除
where ReportsTo is null
WITH cte
(TopNode
,Employee
,ReportsTo
,Depth
,TreePath)
AS
(
SELECT ReportsTo AS TopNode
,Employee
,ReportsTo
,0 AS Depth
,CAST(ReportsTo AS VARCHAR(max)) AS TreePath
FROM #tblTable1
UNION ALL
SELECT cte.TopNode
,a.Employee
,a.ReportsTo
,cte.Depth + 1 AS depth
,CAST(cte.TreePath + ' -> ' +
CAST(a.ReportsTo AS VARCHAR(max))
AS VARCHAR(max)) AS TreePath
FROM #tblTable1 AS a
inner join cte
ON cte.Employee = a.ReportsTo
)
现在您已经拥有了所有节点/分支,您可以选择那些反映您想要的适当深度的节点/分支。(concat还将最终员工添加到树路径中。)
此选择还为顶部节点提供了正确的零深度。
SELECT
cte.Employee
,cte.TopNode AS ReportsTo
,case when cte.ReportsTo is null
then cte.Depth
else cte.Depth + 1
end AS Depth
,case when cte.ReportsTo is null
then cte.Employee
else CAST(cte.TreePath + ' -> ' +
CAST(cte.Employee AS VARCHAR(max))
AS VARCHAR(max))
end AS TreePath
FROM cte
WHERE
cte.TopNode is not null
or cte.ReportsTo is null
ORDER BY
cte.TopNode
,cte.Depth;
结果集为:
Employee ReportsTo Depth TreePath
a NULL 0 a
b a 1 a -> b
c a 2 a -> b -> c
d a 3 a -> b -> c -> d
c b 1 b -> c
d b 2 b -> c -> d
d c 1 c -> d