如何根据具有clasue的select查询中的条件更改列位置

时间:2016-11-22 07:30:58

标签: sql sql-server-2008

在下面的查询中,我已经成功地从1月开始在表中获取数据,但我希望根据给定日期开始月份。 例如:如果month(inputdate)为11,那么表列应该从nov开始并以sep结束

我已尝试使用if else和动态查询,但由于带有子句

而未成功

任何帮助将不胜感激!

WITH taskspecdata AS (select left(datename(month,max(approvalinfo_enddate)),3)as approvedMonth,
year(max(approvalinfo_enddate)) as approvedYear, month(max(approvalInfo_endDate)) as sortMonth,
Document_Id as docid,DocVersion_Counter as versions,docversion_Id as verid
from [webcenter].[WcReports_DocApprovalQ] where
(ApprovalInfo_EndDate)>= DATEADD(year,-1,GETDATE()) and (ApprovalInfo_EndDate)<= GETDATE()
group by [WcReports_DocApprovalQ].DocVersion_Id,Document_Id,DocVersion_Counter)
select versions,
sum(case when approvedMonth = 'Jan' then 1 else 0 end) Jan,
sum(case when approvedMonth = 'Feb' then 1 else 0 end) Feb,
sum(case when approvedMonth = 'Mar' then 1 else 0 end) Mar,
sum(case when approvedMonth = 'Apr' then 1 else 0 end) Apr,
sum(case when approvedMonth = 'May' then 1 else 0 end) May,
sum(case when approvedMonth = 'Jun' then 1 else 0 end) Jun,
sum(case when approvedMonth = 'Jul' then 1 else 0 end) Jul,
sum(case when approvedMonth = 'Aug' then 1 else 0 end) Aug,
sum(case when approvedMonth = 'Sep' then 1 else 0 end) Sep,
sum(case when approvedMonth = 'Oct' then 1 else 0 end) Oct,
sum(case when approvedMonth = 'Nov' then 1 else 0 end) Nov,
sum(case when approvedMonth = 'Dec' then 1 else 0 end) Dec from taskspecdata group by versions

Result columns:

versions    Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec

but i want to start from input month`enter code here`
if given month is nov then

versions    Nov Dec Jan Feb Mar Apr May Jun Jul Aug Sep Oct 

1 个答案:

答案 0 :(得分:0)

select id,Month where id>input data union 
select id,Month where  id<input data