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

北城以北 提交于 2019-11-29 12:35:36

You can use a Calendar or dates table for this sort of thing.

For only 152kb in memory, you can have 30 years of dates in a table with this:

/* dates table */
declare @fromdate date = '20000101';
declare @years    int  = 30;
/* 30 years, 19 used data pages ~152kb in memory, ~264kb on disk */
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
select top (datediff(day, @fromdate,dateadd(year,@years,@fromdate)))
    [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
into dbo.Dates
from n as deka cross join n as hecto cross join n as kilo
               cross join n as tenK cross join n as hundredK
order by [Date];
create unique clustered index ix_dbo_Dates_date
  on dbo.Dates([Date]);

Without taking the actual step of creating a table, you can use it inside a common table expression with just this:

declare @fromdate date = '20161229'; 
declare @thrudate date = '20170103';
;with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, dates as (
  select top (datediff(day, @fromdate, @thrudate)+1) 
      [Date]=convert(date,dateadd(day,row_number() over(order by (select 1))-1,@fromdate))
  from n as deka cross join n as hecto cross join n as kilo
                cross join n as tenK cross join n as hundredK
   order by [Date]
)
select [Date]
from dates;

Use either like so:

select 
    t.AppointmentId
  , StartDate = d.date
  , EndDate = d.date
from dates d
  inner join appointments t
    on d.date >= t.StartDate
   and d.date <= t.EndDate

rextester demo: http://rextester.com/TNWQ64342

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 |
+---------------+------------+------------+

Number and Calendar table reference:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!