日期:2014-05-17  浏览次数:20568 次

如何取动态的日期列名?
我要查询最近12个月的数据,列名也要动态显示,比如我在今天查询,字段名要分别为:2013年1月、2013年2年、……、2013年12月。
当我在下个月再查询此报表的时候,字段名要分别为:2013年2月、2013年3年、……、2014年1月。
这个动态的列名要怎样实现?

------解决方案--------------------
引用:
Quote: 引用:

你得给出你的表,这样就可以结合上面的代码,来写出动态的sql了。


select 
客户,
sum(case when datediff(month,_date,getdate())=1 then 销售金额 else 0 end) as [2013年12月],
sum(case when datediff(month,_date,getdate())=2 then 销售金额 else 0 end) as [2013年11月],
sum(case when datediff(month,_date,getdate())=3 then 销售金额 else 0 end) as [2013年10月],
sum(case when datediff(month,_date,getdate())=4 then 销售金额 else 0 end) as [2013年9月],
sum(case when datediff(month,_date,getdate())=5 then 销售金额 else 0 end) as [2013年8月],
sum(case when datediff(month,_date,getdate())=6 then 销售金额 else 0 end) as [2013年7月],
sum(case when datediff(month,_date,getdate())=7 then 销售金额 else 0 end) as [2013年6月],
sum(case when datediff(month,_date,getdate())=8 then 销售金额 else 0 end) as [2013年5月],
sum(case when datediff(month,_date,getdate())=9 then 销售金额 else 0 end) as [2013年4月],
sum(case when datediff(month,_date,getdate())=10 then 销售金额 else 0 end) as [2013年3月],
sum(case when datediff(month,_date,getdate())=11 then 销售金额 else 0 end) as [2013年2月],
sum(case when datediff(month,_date,getdate())=12 then 销售金额 else 0 end) as [2013年1月] 
from 表
where datediff(month,_date,getdate()) between 1 and 12
group by 客户



当我在下个月查询同样的语句,列名要分别为2014年1月、2013年12月、……、2013年2月。目前的语句列名是固定的,不是我想要的。要怎样写语句呢?


这样:

declare @sql nvarchar(4000)

set @sql = ''


select @sql = @sql + ',sum(case when datediff(month,_date,getdate())='
                   + cast(number+1 as varchar)
                   + ' then 销售金额 else 0 end) as ['
                   + datename(year,DATEADD(MONTH,number,GETDATE()))+'