2015-02-24 69 views
0

有沒有辦法使這項工作?變更靜態「,13月份阿戈」 納入一月基於日期的動態列名更改[T-SQL]

原始

> COUNT(CASE WHEN dateadd(MONTH, - 13, getdate()) > 
> HireDate AND dateadd(MONTH, - 13, getdate()) < 
> TerminationDate OR 
>TerminationDate IS NULL THEN 1 ELSE NULL END) AS 13Monthsago 

首選

> COUNT(CASE WHEN dateadd(MONTH, - 13, getdate()) > 
> HireDate AND dateadd(MONTH, - 13, getdate()) < 
> TerminationDate OR 
>TerminationDate IS NULL THEN 1 ELSE NULL END) AS 
>DATENAME(month, dateadd(MONTH,-13,getdate())) 
+0

如果你問你是否可以生成列名於即時然後看看[動態SQL](https://開頭msdn.microsoft.com/en-us/library/ms709342%28v=vs.85%29.aspx)。然後看[SQL注入](http://bobby-tables.com/)。然後想想你真的想要完成什麼。 – HABO 2015-02-24 18:45:30

+0

好吧,所以它不是那麼簡單...感謝您的建議 – ColorfulWind 2015-02-24 18:47:01

回答

1

一個漫長的做法,但會運行

declare @MonthName varchar(20) 

select 1 num, 'January' name into #Months 
union 
select 2 num, 'February' name 
union 
select 3 num, 'March' name 
union 
select 4 num, 'April' name 
union 
select 5 num, 'May' name 
union 
select 6 num, 'June' name 
union 
select 7 num, 'July' name 
union 
select 8 num, 'August' name 
union 
select 9 num, 'September' name 
union 
select 10 num, 'October' name 
union 
select 11 num, 'November' name 
union 
select 12 num, 'December' name 

select @MonthName = name from #Months where datepart(mm,getdate()) = num 

--Add the other columns to the dataset here 
--This is just an example 
select HireDate, TerminationDate, 
COUNT(CASE WHEN dateadd(MONTH, - 13, getdate()) > 
HireDate AND dateadd(MONTH, - 13, getdate()) < 
TerminationDate OR 
TerminationDate IS NULL THEN 1 ELSE NULL END) AS 13Monthsago 
into #Dataset 
FROM SomeTable GROUP BY HireDate, TerminationDate 

use tempdb 

EXEC sp_RENAME '#Dataset.13Monthsago' , @MonthName, 'COLUMN' 

SELECT * FROM #Dataset 
+0

這完美的作品,謝謝!但是,如何在此查詢中添加12MonthsAgo,11MonthsAgo等? – ColorfulWind 2015-02-25 15:30:07

+0

然後你需要做的是擺脫列名「13MonthAgo」,並有一個通用的名稱,如「SomeTimeAgo」,然後創建'#Dataset13'(13個月),'#Dataset12'(12個月)..並根據上述邏輯重新命名所有'SomeTimeAgo'列。 – SouravA 2015-02-25 15:33:19

0

這可能是去了解它的一種方式。

;with cte_Dates AS 
(
SELECT CAST('20150101' as DATEtime) as DateStr UNION ALL 
SELECT '20150201' UNION ALL 
SELECT '20150202' UNION ALL 
SELECT '20150203' UNION ALL 
SELECT '20150204' UNION ALL 
SELECT '20150301' UNION ALL 
SELECT '20150401' UNION ALL 
SELECT '20150501' UNION ALL 
SELECT '20150601' UNION ALL 
SELECT '20150701' UNION ALL 
SELECT '20150801' UNION ALL 
SELECT '20150901' UNION ALL 
SELECT '20151001' UNION ALL 
SELECT '20151101' UNION ALL 
SELECT '20151201' 
) 


SELECT  * 
FROM 
    (SELECT DateStr,DATENAME(MONTH,DateStr) As MONTHS 
    FROM 
      cte_Dates 
    )P 
     PIVOT 
     ( 
     count(DateStr) 
     FOR MONTHS IN ([January], [February],[March],[April],[May],[June],[July],[August],[September],[October],[November],[December]) 
     )AS PVT