日期:2014-05-18 浏览次数:20522 次
--小计与总计的汇总 declare @t table(name varchar(20),Num int) insert into @t select 'a',1 insert into @t select 'a',2 insert into @t select 'b',3 insert into @t select 'b',4 select name=(case when name is null then 'total' else name end),Num from (SELECT name, SUM(Num) as Num,GROUPING(name) 'grp' FROM @t GROUP BY name WITH ROLLUP) t --实例 declare @t table(单据编号varchar(10),商品编码varchar(10),商品名称varchar(10),进货数量int,成本价money,金额money) insert into @t select 'JH001','0001','营养快线',10,3.5,35 insert into @t select 'JH001','0002','AD钙奶',5,6,30 insert into @t select 'JH002','0001','营养快线',5,3.5,17.5 insert into @t select 'JH002','0002','AD钙奶',30,6,180 select 单据编号=case when n=1 then '总计' when s=1 then '小计' else 单据编号end,商品编码,商品名称,进货数量,成本价,金额 from (select 单据编号,商品编码,商品名称,进货数量=sum(进货数量),成本价=sum(成本价),金额=sum(金额),GROUPING(单据编号)n ,GROUPING(商品编码)s from @t group by 单据编号,商品编码,商品名称 with rollup)a where 商品名称is not null or n=1 or s=1
------解决方案--------------------
你的数据
--> 测试数据: #T1
if object_id('tempdb.dbo.#T1') is not null drop table #T1
create table #T1 ([客户] varchar(1),[编号] int,[货号] varchar(5),[规格] varchar(4),[数] int,[重量] int,[物料] varchar(5),[数量] numeric(2,1),[单价] int,[金额] int)
insert into #T1
select 'A',123,'LH001','20*2',10,12,'123-1',0.1,10,1 union all
select 'A',123,'LH001','20*2',23,11,'123-1',2,15,30 union all
select 'A',123,'LH001','20*2',43,15,'123-1',0.5,10,5 union all
select 'B',567,'LH003','10*5',10,21,'321',1.1,10,11 union all
select 'B',567,'LH003','10*5',40,34,'321',1.6,10,16
select 客户=case when n=1 then '总计' when s=1 then '小计' else 客户 end,编号,货号,规格,数,重量,物料,数量,单价,金额
from
(select 客户,编号,货号,规格,数,重量,物料,数量=sum(数量),单价=avg(单价),金额=sum(金额),GROUPING(客户)n
,GROUPING(编号)s
from #T1
group by 客户,编号,货号,规格,数,重量,物料
with rollup) a
where 物料 is not null or
n=1 or s=1
drop table #T1
/*
客户 编号 货号 规格 数 重量 物料 数量 单价 金额
---- ----------- ----- ---- ----------- ----------- ----- --------------------------------------- ----------- -----------
A 123 LH001 20*2 10 12 123-1 0.1 10 1
A 123 LH001 20*2 23 11 123-1 2.0 15 30
A 123 LH001 20*2 43 15 123-1 0.5 10 5
小计 NULL NULL NULL NULL NULL NULL 2.6 11 36
B 567 LH003 10*5 10 21 321 1.1 10 11
B 567 LH003 10*5 40 34 321 1.6 10 16
小计 NULL NULL NULL NULL NULL