加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql-server – 树结构中的递归和

发布时间:2020-12-12 16:30:22 所属栏目:MsSql教程 来源:网络整理
导读:我在一张桌子上有一个树形结构.该表是可以无休止地嵌套的类的树.每个类别都有一个ProductCount列,它可以告诉产品类别中直接有多少产品(不是求和子类别). Id | ParentId | Name | ProductCount------------------------------------1 | -1 | Cars | 02 | -1 |
我在一张桌子上有一个树形结构.该表是可以无休止地嵌套的类的树.每个类别都有一个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,但不能很好地按照它应该的方式工作.

任何帮助是赞赏!

解决方法

您可以使用递归CTE,您在锚点中获取所有行,并在递归部分中连接以获取子行.记住原始的ID来自锚点部分的别名RootID,并按照RootID分组的主查询中的sum聚合.

SQL Fiddle

MS SQL Server 2012架构设置:

create table T
(
  Id int primary key,ParentId int,Name varchar(10),ProductCount int
);

insert into T values
(1,-1,'Cars',0),(2,'Bikes',1),(3,1,'Ford',10),(4,3,'Mustang',7),(5,'Focus',4);

create index IX_T_ParentID on T(ParentID) include(ProductCount,Id);

查询1:

with C as
(
  select T.Id,T.ProductCount,T.Id as RootID
  from T
  union all
  select T.Id,C.RootID
  from T
    inner join C 
      on T.ParentId = C.Id
)
select T.Id,T.ParentId,T.Name,S.ProductCountIncludingChildren
from T
  inner join (
             select RootID,sum(ProductCount) as ProductCountIncludingChildren
             from C
             group by RootID
             ) as S
    on T.Id = S.RootID
order by T.Id
option (maxrecursion 0)

Results:

| 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 |

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读