测试数据:

create table Test
(
Id int,
ParentId int,
Qty int
)

insert Test 
values(1,0,2),
      (2,1,3),
      (3,1,5),
      (4,2,1),
      (5,2,2),
      (6,2,2),
      (7,3,6),
      (8,3,4),
      (9,7,10),
      (10,8,5),
      (11,8,15),
      (12,8,20)

查看测试数据:

select * from Test

要得到的结果:

 

sql语句:

;with cte as 
(
select *,Id as FinalId from test
union all
select a.*,b.FinalId from test as a,cte as b where a.ParentId=b.Id
)
select  c.*,d.Total 
from test as c 
left join (
select FinalId,SUM(Qty) as Total 
from cte group by FinalId) as d 
on c.Id=d.FinalId

     树形节点从叶子节点到根节点逐级累计求和,方法是找出所有节点(如某一节点)的叶子节点,但是保证每一层的叶子节点的根节点都是该节点。这样,所有的节点都可以找到其对应的子节点,然后,将这些节点分组求和。最后得到的就是每个节点对应的累计之和。

 posted on 2015-08-01 20:05  会飞的金鱼  阅读(1884)  评论(0)    收藏  举报