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

时间:2015-02-24 18:27:22

标签: sql sql-server-2008 tsql ssms

  

有没有办法让这项工作?改变静态,“ 13MonthsAgo ”   进入 1月

原始

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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