标签:
Id |
ParentId |
Qty |
Qty_Sum |
1 |
0 |
1 |
15 |
2 |
1 |
2 |
11 |
3 |
1 |
3 |
3 |
4 |
2 |
4 |
9 |
5 |
4 |
5 |
5 |
CREATE TABLE tMaterial ( Id INT PRIMARY KEY , ParentId INT , Qty INT , Qty_Sum INT ) INSERT INTO tMaterial SELECT 1, 0, 1, 0 UNION ALL SELECT 2, 1, 2, 0 UNION ALL SELECT 3, 1, 3, 0 UNION ALL SELECT 4, 2, 4, 0 UNION ALL SELECT 5, 4, 5, 0 GO
CREATE FUNCTION fn_getQty_Sum(@Id INT) RETURNS INT AS BEGIN DECLARE @Qty_Sum INT SELECT @Qty_Sum = Qty FROM tMaterial WHERE Id = @Id DECLARE @OID INT, @Qty INT DECLARE cursor1 CURSOR FOR SELECT t.ID from tMaterial AS t WHERE t.ParentId = @Id OPEN cursor1 FETCH NEXT FROM cursor1 INTO @OID WHILE @@FETCH_STATUS = 0 BEGIN SET @Qty = dbo.fn_getQty_Sum(@OID) SET @Qty_Sum = @Qty_Sum + @Qty FETCH NEXT FROM cursor1 INTO @OID END CLOSE cursor1 DEALLOCATE cursor1 RETURN @Qty_Sum END UPDATE tMaterial SET Qty_Sum = dbo.fn_getQty_Sum(Id) SELECT * FROM tMaterial
WITH tmp AS ( SELECT t1.*, CAST(CAST(t1.Id AS NVARCHAR) + ‘.‘ AS NVARCHAR(100)) AS node_path FROM tMaterial t1 WHERE t1.ParentId = 0 UNION ALL SELECT t1.*, CAST(t2.node_path + CAST(t1.Id AS NVARCHAR) + ‘.‘ AS NVARCHAR(100)) FROM tMaterial t1 JOIN tmp AS t2 ON t1.ParentId = t2.Id ) , T2 AS ( SELECT t1.Id, t1.ParentId, t1.Qty, sum(t2.qty) AS Qty_Sum FROM tmp t1 JOIN tmp t2 ON t2.node_path LIKE t1.node_path + ‘%‘ GROUP BY t1.Id, t1.ParentId, t1.Qty, t1.Qty_Sum ) UPDATE T1 SET T1.Qty_Sum = T2.Qty_Sum FROM tMaterial T1 JOIN T2 ON T1.Id = T2.Id SELECT *
FROM tMaterial
WITH tmp AS ( SELECT t.Id tm, * FROM tMaterial t UNION ALL SELECT t2.tm tm, t1.* FROM tMaterial t1 JOIN tmp t2 ON t1.ParentId = t2.Id )
SELECT tm, sum(Qty)
FROM tmp
GROUP BY tm
标签:
原文地址:http://www.cnblogs.com/zhaoguan_wang/p/4634759.html