这是我的方法:
Declare @i int
Declare @dt datetime
Set @i=0
Set @dt='2003-12-25' --大部分是25号结帐 While (@i<12)
Begin
Set @strSum=@strSum+'['+Cast((@i+1) as char(2))+'月产值]=Sum(case when 日期 between DateAdd(Month,@i,Replace(''@dt'',''25'',月末时间)) and DateAdd(Month,@i+1,Replace(''@dt'',''25'',月末时间)) then 产值 else 0 end),'Set @strSum=Replace(@strSum,'@i',@i)
Set @strSum=Replace(@strSum,'@dt',@dt)
--Print @strSum
Set @i=@i+1
EndSet @strSum=Substring(@strSum,1,Len(@strSum)-1)
Set @strbanfei='Select '+@strSum+' From 表1 Left Outer Join 表2 on 表1.客户=表2.客户 Group by 客户Exec(@strbanfei)
Declare @i int
Declare @dt datetime
Set @i=0
Set @dt='2003-12-25' --大部分是25号结帐 While (@i<12)
Begin
Set @strSum=@strSum+'['+Cast((@i+1) as char(2))+'月产值]=Sum(case when 日期 between DateAdd(Month,@i,Replace(''@dt'',''25'',月末时间)) and DateAdd(Month,@i+1,Replace(''@dt'',''25'',月末时间)) then 产值 else 0 end),'Set @strSum=Replace(@strSum,'@i',@i)
Set @strSum=Replace(@strSum,'@dt',@dt)
--Print @strSum
Set @i=@i+1
EndSet @strSum=Substring(@strSum,1,Len(@strSum)-1)
Set @strbanfei='Select '+@strSum+' From 表1 Left Outer Join 表2 on 表1.客户=表2.客户 Group by 客户Exec(@strbanfei)
create table 表1(客户 varchar(10),日期 datetime,产值 int)
insert 表1 select '甲','2004-8-9' ,2500
union all select '甲','2004-8-21',3500
union all select '乙','2004-8-9' ,1000
union all select '乙','2004-8-26',3500create table 表2(客户 varchar(10),月末时间 int)
insert 表2 select '甲',22
union all select '乙',25
go--大致就是这样吧
create proc p_qry
@年 int --要查询的年份
as
declare @s nvarchar(4000),@i int,@dt datetime,@dt1 varchar(20),@dt2 varchar(20)
select @s='',@i=0,@dt=dateadd(year,@年-1900,'1900-1-1 08:00')-1
while @i<12
select @dt1=convert(varchar,dateadd(month,@i,@dt),120)
,@i=@i+1
,@s=@s+'
,['+cast(@i as varchar)+'月]=sum(case when a.日期<dateadd(day,b.月末时间,'''
+@dt1+''') and a.日期>=dateadd(month,-1,dateadd(day,b.月末时间,'''
+@dt1+''')) then 产值 else 0 end)'
select @dt1=convert(char(10),@dt+1,120)
,@dt2=convert(char(10),dateadd(year,1,@dt1),120)
exec('select a.客户'+@s+'
from 表1 a,表2 b where a.客户=b.客户 and a.日期>='''+@dt1+''' and a.日期<'''+@dt2+'''
group by a.客户')
go--调用
exec p_qry 2004
go--删除测试
drop proc p_qry
drop table 表1,表2/*--结果客户 1月 2月 3月 4月 5月 6月 7月 8月 9月 10月 11月 12月
---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- -----
甲 0 0 0 0 0 0 0 6000 0 0 0 0
乙 0 0 0 0 0 0 0 1000 3500 0 0 0(所影响的行数为 2 行)
--*/