将每日日期添加到具有日期范围的表中

时间:2019-02-20 22:51:51

标签: sql-server

我希望从包含日期范围的表中获取数据,并将其插入到一个新表中,该表为该日期范围中的每一天添加一个新行,并在其中添加每日日期。前后的结果请参见下文。

enter image description here

2 个答案:

答案 0 :(得分:0)

尝试一下:

    Declare @Tab Table(Deal int,Type varchar(10),person Varchar(10), StartDate DATETIME, EndDate DATETIME)

    Insert into @Tab
    Select 12345,'Gas','Bob','2019/1/1','2019/1/5' Union All
    Select 44444,'Oil','Sue','2019/1/1','2019/1/3'


    ;WITH cte AS
    (
      SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 1)) - 1 AS [Incrementor]
      FROM   [master].[sys].[columns] sc1
      CROSS JOIN [master].[sys].[columns] sc2
    )


    SELECT t.*,DATEADD(DAY, cte.[Incrementor], t.StartDate) As [Date]
    FROM   cte
    CROSS JOIN @Tab t
    WHERE  DATEADD(DAY, cte.[Incrementor], t.StartDate) <= t.EndDate
    Order by t.Deal

答案 1 :(得分:0)

请尝试以下操作:

;WITH rs AS (
    SELECT t.Deal,t.StartDate AS [Date] FROM @Table t 
    UNION ALL 
    SELECT rs.Deal,DATEADD(DAY,1,rs.[Date]) AS [Date]
    FROM rs
    INNER JOIN @Table t ON t.Deal = rs.Deal
    WHERE t.EndDate > rs.[Date]
)
SELECT t.Deal,t.StartDate,t.EndDate,rs.[Date]
FROM @Table t
INNER JOIN rs on rs.Deal = t.Deal
ORDER BY rs.Deal,rs.[Date]
;