How to merge time intervals in SQL Server

前端 未结 7 1704
再見小時候
再見小時候 2021-01-03 01:43

Suppose I have the following an event table with personId, startDate and endDate.

I want to know how much time the person X sp

7条回答
  •  别那么骄傲
    2021-01-03 02:26

    You can use a recursive CTE to build a list of dates and then count the distinct dates.

    declare @T table
    (
      startDate date,
      endDate date
    );
    
    insert into @T values
    ('2011-01-01', '2011-01-05'),
    ('2011-01-04', '2011-01-08'),
    ('2011-01-11', '2011-01-15');
    
    with C as
    (
      select startDate,
             endDate
      from @T
      union all
      select dateadd(day, 1, startDate),
             endDate
      from C
      where dateadd(day, 1, startDate) < endDate       
    )
    select count(distinct startDate) as DayCount
    from C
    option (MAXRECURSION 0)
    

    Result:

    DayCount
    -----------
    11
    

    Or you can use a numbers table. Here I use master..spt_values:

    declare @MinStartDate date
    select @MinStartDate = min(startDate)
    from @T
    
    select count(distinct N.number)
    from @T as T
      inner join master..spt_values as N
        on dateadd(day, N.Number, @MinStartDate) between T.startDate and dateadd(day, -1, T.endDate)
    where N.type = 'P'    
    

提交回复
热议问题