我有一张单表格的树形结构。该表格是一个类别树,可以无限嵌套。每个类别都有一个ProductCount列,用于显示直接在该类别中拥有多少个产品(不包括子类别)。
Id | ParentId | Name | ProductCount
------------------------------------
1 | -1 | Cars | 0
2 | -1 | Bikes | 1
3 | 1 | Ford | 10
4 | 3 | Mustang | 7
5 | 3 | Focus | 4
我想创建一个 SQL 查询,对于每行/类别,它可以给出包括子类别中的产品数量。
上表的输出应为:
Id | ParentId | Name | ProductCount | ProductCountIncludingChildren
--------------------------------------------------------------------------
1 | -1 | Cars | 0 | 21
2 | -1 | Bikes | 1 | 1
3 | 1 | Ford | 10 | 21
4 | 3 | Mustang | 7 | 7
5 | 3 | Focus | 4 | 4
我知道我可能应该使用CTE,但却不能使它像应该的那样正常工作。
非常感谢任何帮助!