我希望使用递归 CTE 来找到所有 childrencount 和 parentcount 以及 path 和 level 和 currentlevel 的 Total 像这样
Id ParentId Name Path Level CurrentLevel ChildrenCount ParentCount
1 NULL a 1 4 1 3 0
3 1 c 3,1 3 2 2 1
4 3 d 4,3,1 2 3 1 2
5 4 f 5,4,3,1 1 4 0 3
2 NULL b 2 5 1 5 0
6 2 g 6,2 4 2 4 1
7 6 h 7,6,2 3 3 3 2
8 7 i 8,7.6.2 2 4 2 3
9 8 j 9,8,7,6,2 1 5 0 4
10 8 k 10,8,7,6,2 1 5 0 4
我尝试了以下代码,但我不知道如何获取childrencount和parentcount以及path和level和currentlevel,如何编码它动态计算它。
CREATE TABLE #temp([id] int, [parentid] int null,[name] varchar(5));
INSERT INTO #temp ([id], [parentid], [name])
VALUES ('1', null,'a')
, ('2', null,'b')
, ('3', '1','c')
, ('4', '3','d')
, ('5', '4','e')
, ('6', '2','f')
, ('7', '6','h')
, ('8', '7','i')
, ('9', '8','j')
, ('10', '8','k')
WITH AllChildrens as
(
SELECT p.*, CAST(P.Id AS VarChar(Max)) as [Path]
FROM Department P where p.ParentId is null
UNION ALL
SELECT P1.*, CAST(P1.Id AS VarChar(Max)) + ',' + M.[Path]
FROM Department P1
INNER JOIN AllChildrens M
ON M.Id = P1.ParentId
)
SELECT Id,ParentId,Name,Path From AllChildrens order by Id