2017-06-09 190 views
0

我有一個包含3列的表。 ID,Start_Date,End_Date.i要打印Start_Date和End_Date之間的所有日期以及ID。 例如,我有表sql server打印兩個日期列之間的所有日期

+----+------------+------------+ 
| ID | Start_Date | End_Date | 
+----+------------+------------+ 
| 1 | 2017-01-01 | 2017-01-05 | 
+----+------------+------------+ 

,我想導致像

+----+------------+ 
| ID | Date  | 
+----+------------+ 
| 1 | 2017-01-01 | 
| 1 | 2017-01-02 | 
| 1 | 2017-01-03 | 
| 1 | 2017-01-04 | 
| 1 | 2017-04-05 | 
+----+------------+ 

回答

0

創建一個所謂的理貨表(見例如這裏:https://dwaincsql.com/2014/03/27/tally-tables-in-t-sql/),並用它來創建「從」之間的所有日期, 「至今。

SELECT TOP 1000000 N=IDENTITY(INT, 1, 1) 
INTO dbo.Tally 
FROM master.dbo.syscolumns a CROSS JOIN master.dbo.syscolumns b; 
go 

declare @dateFrom datetime = '20170101'; 
declare @dateTo datetime = '20170105'; 

select dateadd(day, N - 1, @dateFrom) 
    from Tally 
where N between 1 and datediff(day, @dateFrom, @dateTo) + 1 

或者:

select dateadd(day, t.N - 1, o.DateFrom) 
    from Tally t 
cross join OtherTable o 
where t.N between 1 and datediff(day, o.DateFrom, o.DateTo) + 1 

理貨表是這樣的情況是非常有用的,它也可以在第二列裝滿日期,從1900-01-01左右開始。

+0

@IgoB我不想聲明變量。我只想從表格欄獲得日期 –

+0

@nanibathineni:這只是一個例子。您可以將其更改爲您的列名稱。 – Wanderer

1

使用公共表表達式:

DECLARE @StartDT DATETIME = '2017-01-01' 
    DECLARE @EndDT DATETIME = '2017-01-05' 
    DECLARE @Id INT = 1 

    ;WITH CTE (_id , _Date)AS 
    (
    SELECT @Id , @StartDT 
    UNION ALL 
    SELECT @Id , DATEADD(DAY,1,_Date) 
    FROM CTE 
    WHERE _Date < @EndDT 
    ) 

    SELECT * FROM CTE 
+0

無需聲明日期我是否可以傳遞列日期 –

+0

+1 @nanibathineni您還應在末尾添加'option(maxrecursion 0)'SELECT * FROM CTE選項(maxrecursion 0)'以避免日期範圍超過100天。 – GauravKP

0
DECLARE @StartDT DATETIME = '2017-01-01' 
    DECLARE @EndDT DATETIME = '2017-01-05' 
    DECLARE @Id INT = 1 

SELECT RANK() OVER (
     ORDER BY (SELECT 1)) AS SeqNo 
     ,CAST (Start_Date AS DATE) AS Start_Date 
FROM (
    SELECT @StartDT + Row_Number() OVER (ORDER BY Rno) - 1 AS Start_Date 
    FROM (
     SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) - 1 AS Rno 
      FROM master..spt_values 
     ) Dt 
    ) Dt2 
WHERE Dt2.Start_Date <= @EndDT 

輸出

SeqNo Start_Date 
    -------------------- 
    1  2017-01-01 
    1  2017-01-02 
    1  2017-01-03 
    1  2017-01-04 
    1  2017-01-05 
相關問題