基于日期 [T-SQL] 的动态列名称更改

Dynamic column name change based on date [T-SQL]

Is there a way to make this work? change static, "13MonthsAgo" into January?

原创

> 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()))

这可能是一种解决方法。

;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 

一个冗长的方法,但会奏效..

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