用SQL实现统计报表中的"小计"与"合计"的方法详解
程序员文章站
2024-02-21 08:32:10
客户提出需求,针对某一列分组加上小计,合计汇总。网上找了一些有关sql加合计的语句。都不是很理想。决定自己动手写。思路有三个:1.很多用groupping和rollup来实...
客户提出需求,针对某一列分组加上小计,合计汇总。网上找了一些有关sql加合计的语句。都不是很理想。决定自己动手写。
思路有三个:
1.很多用groupping和rollup来实现。
优点:实现代码简洁,要求对groupping和rollup很深的理解。
缺点:低版本的sql server不支持。
2.游标实现。
优点:思路逻辑简洁。
缺点:复杂和低效。
3.利用临时表。
优点:思路逻辑简洁,执行效率高。sql实现简单。
缺点:数据量大时耗用内存.
综合三种情况,决定“利用临时表”实现。
实现效果
原始表tb
加上小计,合计后效果
sql语句
复制代码 代码如下:
select * into #tb from tb
select * into #tb1 from #tb where 1<>1
select distinct zcxt into #tbype from #tb order by zcxt
select identity(int,1,1) fid,zcxt into #tbype1 from #tbype
declare @i int
declare @k int
select @i=count(*) from #tbype
set @k=0
declare @strfname varchar(50)
while @k < @i
begin
set @k =@k +1
select @strfname=zcxt from #tbype1 where fid =@k
set identity_insert #tb1 on
insert into #tb1(fid,qldid,fa_cardid,ztbz,fa_name,model,i_number,gzrq,zcyz,ljzj,jz,sybm,zcxt,fa_ljjzzb)
select fid,qldid,fa_cardid,ztbz,fa_name,model,i_number,gzrq,zcyz,ljzj,jz,sybm,zcxt,fa_ljjzzb from
(
select * from #tb where zcxt=@strfname
union all
select 0 fid,'' qldid,'' fa_cardid,'' ztbz,'小计' fa_name,'' model,sum(i_number) as i_number,'' gzrq,sum(cast(zcyz as money)) as zcyz,sum(cast(ljzj as money)) as ljzj,sum(cast(jz as money)) as jz,'' sybm,'' zcxt,sum(fa_ljjzzb) as fa_ljjzzb
from #tb where zcxt=@strfname
group by ztbz
) as b
set identity_insert #tb1 off
end
select qldid,fa_cardid,zcxt,fa_name,model,i_number,gzrq,zcyz,ljzj,jz,sybm,ztbz,fa_ljjzzb from #tb1
union all
select '' qldid,'' fa_cardid,'' ztbz,'合计' fa_name,'' model,sum(i_number) as i_number,'' gzrq,sum(cast(zcyz as money)) as zcyz,sum(cast(ljzj as money)) as ljzj,sum(cast(jz as money)) as jz,'' sybm,'' zcxt,sum(fa_ljjzzb) as fa_ljjzzb
from #tb
drop table #tb1
drop table #tbype1
drop table #tbype
drop table #tb
扩展改进
可以改写成一个通用的添加合计小计的存储过程。
上一篇: 使用SQL实现小计,合计以及排序