客戶提出需求,針對某一列分組加上小計,合計匯總。網上找了一些有關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
擴展改進
可以改寫成一個通用的添加合計小計的存儲過程。