仓库编号 商品编号, 数量
1 a1 100
1 a1 50
1 a2 30
2 a1 60
2 a2 40
3 a2 80
我现在要做一个报表
a1 仓库编号 数量
NULL 1 150
NULL 2 60
合计 NULL 210
a2 仓库编号 数量
NULL 1 30
NULL 2 40
NULL 3 80
合计 NULL 150
select * from into #t
(
select distinct 商品编号 , 仓库编号 仓库编号 , 数量 数量 ,1 flag1,商品编号 flag2 from 表
union all
select null,仓库编号,cast(sum(数量) as varchar),2,商品编号 from 表 group by 商品编号,仓库编号
union all
select distinct 合计,null ,null,4,商品编号 from 表) a
order by flag2,flag1
update #t
set 数量=a.数量
from
(select cast(sum(cast (数量 as int)) as varchar) 数量 ,flag1,flag2
from #t where 数量<>数量 group by flag,flag2)a
where #t.flag2=a.flag2 and #t.商品编号=合计
select 商品编号,仓库编号,数量 from #t
select 商品编号,仓库编号,数量 from (
select distinct 商品编号,仓库编号 仓库编号,数量 数量,0 flag1,商品编号 flag2 from 表
union all
select null,cast(仓库编号 as varchar(10)),cast(sum(数量) as varchar(10)),1,商品编号 from 表 group by 商品编号,cast(仓库编号 as varchar(10))
union all
select 合计,null,sum(数量),2,商品编号 from 表 group by 商品编号) tem order by flag2,flag1