问题描述
我希望像这样使用递归 CTE 为所有 childcount 和 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,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,2 1 5 0 4
10 8 k 10,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','b'),('3','1','c'),('4','3','d'),('5','4','e'),('6','2','f'),('7','6','h'),('8','7','i'),('9','8','j'),('10','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
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)