22,207
社区成员
发帖
与我相关
我的任务
分享
declare @sql varchar(8000), @dt1 datetime, @dt2 datetime
set @dt1 = '2008-1-1'
set @dt2 = '2009-12-31'
set @sql = 'select fcode'
select @sql = @sql + ', sum(case convert(char(6), 日期, 112) when ''' + 年月 + ''' then 金额 else 0 end) as [f' + 年月 + ']'
from (select distinct convert(char(6), 日期, 112) as 年月 from 表 where 日期 between @dt1 and @dt2) as a order by 年月
set @sql = @sql + ' FROM 表 where convert(char(6), 日期, 112) between ''' + convert(char(6), @dt1, 112) + ''' and ''' + convert(char(6), @dt2, 112) + ''' group by fcode'
exec(@sql)
select fcode, sum(case when convert(char(6), fdate, 112) = '200801' then amt else 0 end) as [200801],
sum(case when convert(char(6), fdate, 112) = '200802' then amt else 0 end) as [200802],
sum(case when convert(char(6), fdate, 112) = '200803' then amt else 0 end) as [200803],
sum(case when convert(char(6), fdate, 112) = '200804' then amt else 0 end) as [200804],
sum(case when convert(char(6), fdate, 112) = '200805' then amt else 0 end) as [200805],
sum(case when convert(char(6), fdate, 112) = '200806' then amt else 0 end) as [200806],
sum(case when convert(char(6), fdate, 112) = '200807' then amt else 0 end) as [200807],
sum(case when convert(char(6), fdate, 112) = '200808' then amt else 0 end) as [200808],
sum(case when convert(char(6), fdate, 112) = '200809' then amt else 0 end) as [200809],
sum(case when convert(char(6), fdate, 112) = '200810' then amt else 0 end) as [200810],
sum(case when convert(char(6), fdate, 112) = '200811' then amt else 0 end) as [200811],
sum(case when convert(char(6), fdate, 112) = '200812' then amt else 0 end) as [200812]
into #DepYearDes from ktk_gck group by fcode