declare @t table(a varchar(10),b int)
insert into @t
select '王',12 union all
select '李',10 union all
select '王',20 union all
select '张',30
select * from (
select id=count(a)+1,a=a+'(小计)',b=sum(b) from @t group by a
union all
select id=(select count(1) from @t where t.a=a and t.b<=b),*
from @t t) d
order by a,id
declare @t table(a varchar(10),b int)
declare @tt table(id int identity(1,1),a varchar(10),b int)
insert into @t
select '王',12 union all
select '李',10 union all
select '王',20 union all
select '张',30
insert into @tt
select a= case when grouping(b)=1 then a + '(小计)' else a end,b = sum(b)
from @t
group by a,b with rollup
having grouping(a)=0