Break into multiple rows based on date range of a single row

前端 未结 2 1708
盖世英雄少女心
盖世英雄少女心 2020-12-20 07:09

I have a table which captures appointments, some are single day appointments and some are multi day appointments, so the data looks like

AppointmentId   Star         


        
2条回答
  •  天涯浪人
    2020-12-20 07:21

    Clearly a Calendar/Tally table would be the way to go as SqlZim illustrated (+1), however you can use an ad-hoc tally table with a CROSS APPLY.

    Example

    Select A.AppointmentId   
          ,StartDate = B.D  
          ,EndDate   = B.D
     From  YourTable A
     Cross Apply (
                    Select Top (DateDiff(DD,A.StartDate,A.EndDate)+1) D=DateAdd(DD,-1+Row_Number() Over (Order By Number),A.StartDate) 
                     From  master..spt_values
                 ) B
    

    Returns

    AppointmentId   StartDate   EndDate
    9               2017-04-12  2017-04-12
    10              2017-05-01  2017-05-01
    10              2017-05-02  2017-05-02
    10              2017-05-03  2017-05-03
    11              2017-06-01  2017-06-01
    

提交回复
热议问题