大家在SQL编程过程如都会遇到需要对数据进行分组并对组内资料进行处理的情况,如组内求和,即小计。苦闷了许久之后终于想到了一个方法,与大家分享之。 以下就是一种较直观易懂的方法。 --创建用于测试资料表 CREATE table Items ( ItemID int primary key identity(1,1), ItemA varchar(1) not null, ItemB varchar(2) not null, Quantity int not null ) --新增150笔资料 declare @i int set @i=0 while @i<150 begin insert into Items values(char(cast(26*rand()+65 as int)),char(cast(26*rand()+65 as int)),cast(100*rand() as int)) set @i=@i+1 end --以字段ItemA,ItemB来分组,先以ItemA,ItemB排序并将资料导入临时表中。 select cast(row_number() over(order by ItemA,ItemB) as decimal(10,1)) as ItemID,ItemA,ItemB,Quantity into #T from Items --获取统计数据,取max(ItemID)+0.5为便于排序. select max(ItemID)+0.5 NewItemID,sum(Quantity) subTotal,ItemA,ItemB into #T2 from #T group by ItemA,ItemB order by ItemA,ItemB --获取最终数据 select ItemID,ItemA,ItemB,Quantity from ( select ItemID,ItemA,ItemB,Quantity from #T union all select NewItemID,'','合计:',subTotal from #T2 ) a order by ItemID 最终效果如下图。