Convert Date Range to Individual Days

后端 未结 2 1429
终归单人心
终归单人心 2021-01-22 23:12

A table called VolumeRequest stores the volume requests by accounts for a date range.

AccountId   StartDate                       EndDate                    


        
2条回答
  •  鱼传尺愫
    2021-01-22 23:49

    SQLFiddle demo

    Using WITH clause and recursion we generate Days table with all days between MIN and MAX dates. Then generate table Accounts with distinct AccountID. Finally JOIN all these tables and group all with SUM.

    WITH MINMAX as 
    ( SELECT MIN(StartDate) as MinDate,
             MAX(EndDate) as MaxDate
      from T
    ),
    DAYS as
    ( SELECT MinDate as D from MINMAX
      UNION ALL
      SELECT D+1 as D FROM DAYS WHERE D+1<=
        (
          SELECT MaxDate FROM MINMAX  
         )
    ),
    Accounts as 
    (
      select distinct AccountID from T
    ) 
    
    select A.AccountId,Days.D,sum(T.DailyVolume) from Days
    CROSS JOIN Accounts A 
    JOIN T on A.AccountID=T.AccountID
              AND
              Days.D between T.StartDate and T.EndDate
    GROUP BY A.AccountId,Days.D
    ORDER BY A.AccountId,Days.D
    OPTION (MAXRECURSION 10000)
    

提交回复
热议问题