T1 Id parentid M N E m F m X f Y f Z B T2 Row id amount 1 a 13.00 2 B 20.00 3 e 20.00 4 f 20.00 5x20.00 6 y 20.00 7 z 20.00 8 e 12.00 9x11.00 10 f 13.00 How to get the following results: Row id amount 7x20.00 11x11.00 X subtotal 31.00 8 y 20.00 Y 20.00 6 f 20.00 12 f 13.00 F subtotal 84.00 5 e 20.00 10 e 12.00 E subtotal 32.00. 3 m 14.00 M subtotal 130.00 4 n 13.00 N subtotal 13.00 1 a 13.00 A. Subtotal 156.00 9 z 20.00 Z subtotal 20.00 2 B 20.00 Subtotal B 40.00 Total 196.00 Implementation Program -- Sample Data Create table t1 ( Id char (1 ), Parentid char (1) ); INSERT t1 SELECT 'M', 'A' UNION ALL SELECT 'n', 'A' UNION ALL SELECT 'E', 'M' UNION ALL SELECT 'F', 'M' UNION ALL SELECT 'x', 'F' UNION ALL SELECT 'y', 'F' UNION ALL SELECT 'Z', 'B '; Create table t2 ( Row int, Id char (1 ), Amount decimal (10, 2) ); INSERT t2 SELECT '1', 'A', '13. 00' UNION ALL SELECT '2', 'B', '20. 00' UNION ALL SELECT '3', 'E', '20. 00' UNION ALL SELECT '4', 'F', '20. 00' UNION ALL SELECT '5', 'x', '20. 00' UNION ALL SELECT '6', 'y', '20. 00' UNION ALL SELECT '7', 'z', '20. 00' UNION ALL SELECT '8', 'E', '12. 00' UNION ALL SELECT '9', 'x', '11. 00' UNION ALL SELECT '10', 'F', '13. 00 '; GO -- Statistics -- Level-by-level Summary Declare @ l int Set @ l = 1 Select A. [id], [Pid] = A. parentid, [Sumnum] = SUM (B. amount ), Level = case When exists (select * from t1 where parentid = a. [id]) Then @ L-1 else @ l end Into [#] From t1 Left join t2 B On a. id = B. id Group by a. id, A. parentid; If @ row/42852.htm target = _ blank> count> 0 Create index IDX _ # _ id_pid on [#] ([id], [pid]) Else Set @ l = 999 While @ rowcount> 0 or @ l = 1 Begin Set @ l = @ l + 1 Update a set level = @ l, [sumnum] = isnull (a. [sumnum], 0) + isnull (B. [sumnum], 0) From [#] ,( Select aa. pid, [sumnum] = sum (aa. [sumnum]) From [#] aa ,( Select distinct [pid] from [#] Where level = L-1 ) Bb where aa. [pid] = bb. [pid] And not exists ( SELECT * FROM [#] WHERE [PID] = aa. [PID] AND [Level] = 0) Group by aa. [PID] Having sum (case when aa. level = 0 then 1 else 0 end) = 0 ) B where a. [id] = B. [pid] End -- Final Result SELECT Row = CASE When grouping (A. row) = 0 then rtrim (A. row) ELSE n'' END, Id = CASE When grouping (A. row) = 0 then a. id When grouping (A. id) = 0 then a. id + 'subtotal' Else n 'Total' END, Amount = CASE When grouping (A. row) = 0 then sum (A. amount) When grouping (A. id) = 0 then isnull (select sum (B. sumnum) FROM # B where a. id = B. id), SUM (A. amount )) Else sum (A. amount) END FROM t2 Group by a. id, A. row with rollup; Drop table [#] GO Drop table t1, t2; /* -- Result Row id amount -------------------------------------------------------- 1 a 13.00 A. Subtotal 13.00 2 B 20.00 Subtotal B 20.00 3 e 20.00 8 e 12.00 E subtotal 32.00. 4 f 20.00 10 f 13.00 F subtotal 84.00 5x20.00 9x11.00 X subtotal 31.00 6 y 20.00 Y 20.00 7 z 20.00 Z subtotal 20.00 Total 169.00 (18 rows affected) --*/ |