通过transpose在sql中的单个列中存储日期?

时间:2017-06-12 18:59:40

标签: sql sql-server

我试图生成一个列,其中包含各个月末的日期列表以及今天的日期。到目前为止,我有:

DECLARE @date DATETIME = '7/1/2016';  
SELECT 
CONVERT(char(10), GetDate(),126)
,EOMONTH ( @date, 1 ) 
,EOMONTH (@date, 2)  
,EOMONTH (@date, 3)  
,EOMONTH (@date, 4)  
,EOMONTH (@date, 5)  
,EOMONTH (@date, 6)  
,EOMONTH (@date, 7)  
,EOMONTH (@date, 8)  
,EOMONTH (@date, 9)  
,EOMONTH (@date, 10)
,EOMONTH (@date, 11)
,EOMONTH (@date, 12) ;  
GO 

但是这给了我一个输出,其中每个结果都是一个新列。有没有办法转换此输出,因此它只是一列,每个新结果都是一个新行?

3 个答案:

答案 0 :(得分:2)

如果我理解正确,我会使用VALUES

DECLARE @date DATETIME = '2016-07-01';

SELECT  v.*
FROM (VALUES (@date),
             (EOMONTH(@date, 1)) ,
             (EOMONTH(@date, 2)), 
             (EOMONTH(@date, 3)), 
             (EOMONTH(@date, 4)),
             (EOMONTH(@date, 5)),
             (EOMONTH(@date, 6)),
             (EOMONTH(@date, 7)),
             (EOMONTH(@date, 8)),
             (EOMONTH(@date, 9)),
             (EOMONTH(@date, 10)),
             (EOMONTH(@date, 11)),
             (EOMONTH(@date, 12))
            ) v(dte);  

答案 1 :(得分:0)

一种方法是使用递归cte:

DECLARE @date DATE = '2016-07-01';  

;WITH CTE AS
(
    SELECT 1 As n
    UNION ALL
    SELECT n + 1
    FROM CTE
    WHERE n < 12
)
SELECT n, EOMONTH (@date, n)
FROM CTE

See a live demo on rextester

另一种可能更好的方法是使用计数表 如果您不知道计数表是什么以及为什么它对您有好处,read this article by Jeff Moden

如果您还没有计数表,请创建一个:

SELECT TOP 10000 IDENTITY(int,1,1) AS Number
    INTO Tally
    FROM sys.objects s1       
    CROSS JOIN sys.objects s2 
ALTER TABLE Tally ADD CONSTRAINT PK_NumbersTest PRIMARY KEY CLUSTERED (Number)

然后你的代码就像那样简单:

DECLARE @date DATE = '2016-07-01';  

SELECT Number, EOMONTH (@date, Number)
FROM Tally
WHERE Number < 13

Live demo for a tally table

答案 2 :(得分:0)

示例

Declare @Date date = '7/1/2016';  
Declare @Mnth int  = 12     -- << Optional allows you to define the # of months

Select D = @Date
Union All
Select Top (@Mnth) EOMonth(@Date,Row_Number() Over (Order By (Select NULL))) 
 From  master..spt_values    -- << Virtually any Table Will Do

<强>返回

D
2016-07-01
2016-08-31
2016-09-30
2016-10-31
2016-11-30
2016-12-31
2017-01-31
2017-02-28
2017-03-31
2017-04-30
2017-05-31
2017-06-30
2017-07-31