我有这种结构的表:
Id ParentId CountItems
我可以通过脚本计算项目的级别:
;WITH cteSort AS
(
SELECT Id AS Child, ParentId AS Parent, 1 AS [Level]
FROM [Catalog].[Category] WHERE Id = 0
union ALL
SELECT Id AS Child, ParentId AS Parent, [Level] + 1 AS [Level]
FROM [Catalog].[Category]
INNER JOIN cteSort ON [Category].ParentId = cteSort.Child and Id <>0)
我想从较低级别上升到顶部,并将站在较低级别和当前 CountItems 的字段 CountItems 子项的总和放入当前 CountItems。像这样:之前
Id ParentId count
0 0 0
1 0 1
2 0 1
3 1 1
4 1 1
5 2 1
6 3 1
7 4 1
8 4 1
后
Id ParentId count
0 0 8
1 0 6
2 0 2
3 1 2
4 1 3
5 2 1
6 3 1
7 4 1
8 4 1