declare @hu table (t varchar(20),K int,A1 int,A2 int,A3 int,A4 int,B int,C1 int,C2 int,C3 int) insert into @hu select '2007年1月',1,1,1,1,1,1,1,1,1 insert into @hu select '2007年2月',2,2,2,2,2,2,2,2,2 insert into @hu select '2007年3月',3,3,3,3,3,3,3,3,3 insert into @hu select '2007年4月',4,4,4,4,4,4,4,4,4 insert into @hu select '2007年5月',5,5,5,5,5,5,5,5,5 insert into @hu select '2007年6月',6,6,6,6,6,6,6,6,6 insert into @hu select '2007年7月',7,7,7,7,7,7,7,7,7 insert into @hu select '2007年8月',8,8,8,8,8,8,8,8,8 insert into @hu select '2007年9月',9,9,9,9,9,9,9,9,9 insert into @hu select '2007年10月',10,10,10,10,10,10,10,10,10 insert into @hu select '2007年11月',11,11,11,11,11,11,11,11,11 insert into @hu select '2007年12月',12,12,12,12,12,12,12,12,12 declare @y varchar(10),@m varchar(10) set @y = 2007 --2007年 set @m = '' --全年 --set @m = 1 --1月 declare @t table(oid varchar(50),t varchar(20),k varchar(5),a1 varchar(5),a2 varchar(5),a3 varchar(5),a4 varchar(5), b varchar(5),c1 varchar(5),c2 varchar(5),c3 varchar(5)) insert @t select '9A' oid,@y+'年累计',sum(k),sum(a1),sum(a2),sum(a3),sum(a4),sum(b),sum(c1),sum(c2),sum(c3) from @hu where left(t,4) = @y insert @t select '9B',@y+'年总计',k,'','','', convert(int,a1)+convert(int,a2)+convert(int,a3)+convert(int,a4),b,'','', convert(int,c1)+convert(int,c2)+convert(int,c3) from @t insert @t select case len(t) when 7 then '0' else '' end+right(t,len(t)-5)+'A', t,k,a1,a2,a3,a4,b,c1,c2,c3 from @hu where left(t,4) = @y and(t = @y+'年'+@m+'月' or @m = '') insert @t select case len(t) when 7 then '0' else '' end+right(t,len(t)-5)+'B', replace(t,'年','-')+'小计',K,'','','',a1+a2+a3+a4,b,'','',c1+c2+c3 from @hu where left(t,4) = @y and(t = @y+'年'+@m+'月' or @m = '') select t,k,a1,a2,a3,a4,b,c1,c2,c3 from @t order by oid /* t k a1 a2 a3 a4 b c1 c2 c3 -------------------- ----- ----- ----- ----- ----- ----- ----- ----- ----- 2007年1月 1 1 1 1 1 1 1 1 1 2007-1月小计 1 4 1 3 2007年2月 2 2 2 2 2 2 2 2 2 2007-2月小计 2 8 2 6 2007年3月 3 3 3 3 3 3 3 3 3 2007-3月小计 3 12 3 9 2007年4月 4 4 4 4 4 4 4 4 4 2007-4月小计 4 16 4 12 2007年5月 5 5 5 5 5 5 5 5 5 2007-5月小计 5 20 5 15 2007年6月 6 6 6 6 6 6 6 6 6 2007-6月小计 6 24 6 18 2007年7月 7 7 7 7 7 7 7 7 7 2007-7月小计 7 28 7 21 2007年8月 8 8 8 8 8 8 8 8 8 2007-8月小计 8 32 8 24 2007年9月 9 9 9 9 9 9 9 9 9 2007-9月小计 9 36 9 27 2007年10月 10 10 10 10 10 10 10 10 10 2007-10月小计 10 40 10 30 2007年11月 11 11 11 11 11 11 11 11 11 2007-11月小计 11 44 11 33 2007年12月 12 12 12 12 12 12 12 12 12 2007-12月小计 12 48 12 36 2007年累计 78 78 78 78 78 78 78 78 78 2007年总计 78 312 78 234 (所影响的行数为 26 行) */