日期:2014-05-18  浏览次数:20448 次

怎样来查询出这样的列名?
比如2012年3月份查询数据,那么上一个月出库的总数量列名要显示为:2012年2月
同理当你在2012年4月份查询数据时,那么上一个月出库的总数量列名要显示为:2012年3月
即列名会根据当前的查询时间自动判断,然后给出相应的列名。

sum(case when datediff(month,_date,getdate())=1 then 出库数量 else 0 end) “?”-- 这里该怎样填写

因为我想要做的查询是能自动显示前一个月的出库数量,因此列名也要相应的改变。

------解决方案--------------------
sum(case when datediff(month,_date,getdate())=1 then 出库数量 else 0 end) as ltrim(year(getdate()))+'年'+ltrim(month(getdate())-1)+'月'
------解决方案--------------------
SQL code

select ltrim(year(getdate()))+'年'+ltrim(month(getdate())-1)+'月'
(无列名)
2012年2月


sum(case when datediff(month,_date,getdate())=1 then 出库数量 else 0 end) as ltrim(year(getdate()))+'年'+ltrim(month(getdate())-datediff(month,_date,getdate()))+'月'
--更正如上,这样的话你就可以自动显示出每个月的了

------解决方案--------------------
declare @mm as varchar(7)
set @mm = convert(varchar(7),dateadd(mm,-1,getdate()),120)

exec('select sum(case when datediff(month,_date,getdate())=1 then 出库数量 else 0 end) as + '[' + @mm + '] from tb')