日期:2014-05-18 浏览次数:20583 次
declare @i int set @i=1 while @i<=3 begin .......//你的统计语句 end
------解决方案--------------------
忘了累加了 declare @i int set @i=1 while @i<=3--3表示你的月份 begin .......--你的统计语句 set @i=@i+1 end
------解决方案--------------------
--> 测试数据: # if object_id('tempdb.dbo.#') is not null drop table # create table # (f27 int,f28 int,f8 int,dw varchar(1),tbsj datetime) insert into # select 2,1,1,'A','2007-01-01' union all select 2,1,1,'B','2007-01-01' union all select 2,1,1,'A','2007-02-01' union all select 2,1,1,'B','2007-02-01' union all select 2,1,1,'A','2008-01-01' union all select 2,1,1,'B','2008-01-01' union all select 2,1,1,'A','2008-02-01' union all select 2,1,1,'B','2008-02-01' declare @tbsj datetime set @tbsj = '20080301' select dw=isnull(a.dw,b.dw), f27本年=a.f27, f28本年=a.f28, f8本年=a.f8, f27上年=b.f27, f28上年=b.f28, f8上年=b.f8 from ( select dw,sum(f27)f27,sum(f28)f28,sum(f8)f8 from # where year(tbsj)=year(@tbsj) and month(tbsj)<=month(@tbsj) group by dw ) a full join ( select dw,sum(f27)f27,sum(f28)f28,sum(f8)f8 from # where year(tbsj)=year(@tbsj)-1 and month(tbsj)<=month(@tbsj) group by dw ) b on a.dw=b.dw /* dw f27本年 f28本年 f8本年 f27上年 f28上年 f8上年 ---- ----------- ----------- ----------- ----------- ----------- ----------- A 4 2 2 4 2 2 B 4 2 2 4 2 2 */