日期:2014-05-17  浏览次数:20606 次

求和(父节点是所有子节点的和)
类似表
ID,ParentID,Amount
1,0,12
2,1,23
3,1,37
4,2,60

结果
1,0,132
2,1,83
3,1,37
4,2,60

最好有递归与非递归两种算法

------解决方案--------------------
SQL code
create table #data (ID int,ParentID int,Amount int)
insert #data select 1,0,12
insert #data select 2,1,23
insert #data select 3,1,37
insert #data select 4,2,60

;with cte as
(
    select mid=ID, pid=ParentID, * from #data
    union all
    select a.mid, a.pid, b.* from cte a join #data b on a.ID=b.ParentID
)
select ID=mid, ParentID=pid, Amount=sum(Amount) from cte group by mid, pid

/*
结果
1,0,132
2,1,83
3,1,37
4,2,60
*/

------解决方案--------------------
SQL code
--> 测试数据:[tb]
IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb]
GO
CREATE TABLE [tb]([ID] INT,[ParentID] INT,[Amount] INT)
INSERT [tb]
SELECT 1,0,12 UNION ALL
SELECT 2,1,23 UNION ALL
SELECT 3,1,37 UNION ALL
SELECT 4,2,60
GO

--> 测试语句:
; with t as
(
SELECT * FROM [tb] 
union all
select b.id,b.[ParentID],t.[Amount] from tb as b join t on b.id=t.ParentID
)
--1
--SELECT ID, ParentID, Amount=sum(Amount) from t group by ID, ParentID
--2
SELECT * FROM [tb] as a cross apply(select sum([Amount]) as [Amount]  from t where a.id=t.id) app
/*
ID    ParentID    Amount    Amount
1    0    12    132
2    1    23    83
3    1    37    37
4    2    60    60
*/