t1
id parentid
m a
n a
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
5 x 20.00
6 y 20.00
7 z 20.00
8 e 12.00
9 x 11.00
10 f 13.00
如何得出如下结果:
row id amount
7 x 20.00
11 x 11.00
x小计 31.00
8 y 20.00
y小计 20.00
6 f 20.00
12 f 13.00
f小计 84.00
5 e 20.00
10 e 12.00
e小计 32.00
3 m 14.00
m小计 130.00
4 n 13.00
n小计 13.00
1 a 13.00
a小计 156.00
9 z 20.00
z小计 20.00
2 b 20.00
b小计 40.00
总计 196.00
实现程序
-- 示例数据
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
-- 统计
-- 逐级汇总
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 A
LEFT JOIN t2 B
ON A.id = B.id
GROUP BY A.id, A.parentid;
if @@rowsqlserver/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 [#] a,(
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
-- 最终结果
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 + '小计'
ELSE N'总计'
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 A
GROUP BY A.id, A.row WITH ROLLUP;
drop table [#]
GO
DROP TABLE t1, t2;
/*-- 结果
row id amount
------------ ----- ---------------------------------------
1 a 13.00
a小计 13.00
2 b 20.00
b小计 20.00
3 e 20.00
8 e 12.00
e小计 32.00
4 f 20.00
10 f 13.00
f小计 84.00
5 x 20.00
9 x 11.00
x小计 31.00
6 y 20.00
y小计 20.00
7 z 20.00
z小计 20.00
总计 169.00
(18 行受影响)
--*/
|