Find conflicted date intervals using SQL

前端 未结 5 1300
梦谈多话
梦谈多话 2021-01-05 18:28

Suppose I have following table in Sql Server 2008:

ItemId StartDate   EndDate
1      NULL        2011-01-15
2      2011-01-16  2011-01-25
3      2011-01-26           


        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-05 18:35

    I've always taken a slightly different approach to the design if I have data that is never to have overlapping intervals... namely don't store intervals, but only start times. Then, have a view that helps with displaying the intervals.

    CREATE TABLE intervalStarts
    (
      ItemId      int,
      IntervalId  int,
      StartDate   datetime
    )
    
    CREATE VIEW intervals
    AS
    with cte as (
      select ItemId, IntervalId, StartDate,
         row_number() over(partition by IntervalId order by isnull(StartDate,'1753-01-01')) row
      from intervalStarts
    )
    select c1.ItemId, c1.IntervalId, c1.StartDate,
      dateadd(dd,-1,c2.StartDate) as 'EndDate'
    from cte c1
      left join cte c2 on c1.IntervalId=c2.IntervalId
                        and c1.row=c2.row-1
    

    So, sample data might look like:

    INSERT INTO intervalStarts
    select 1, 1, null union
    select 2, 1, '2011-01-16' union
    select 3, 1, '2011-01-26' union
    select 4, 2, null union
    select 5, 2, '2011-01-26' union
    select 6, 2, '2011-01-14'
    

    and a simple SELECT * FROM intervals yields:

    ItemId | IntervalId | StartDate  | EndDate
    1      | 1          | null       | 2011-01-15
    2      | 1          | 2011-01-16 | 2011-01-25
    3      | 1          | 2011-01-26 | null
    4      | 2          | null       | 2011-01-13
    6      | 2          | 2011-01-14 | 2011-01-25
    5      | 2          | 2011-01-26 | null
    

提交回复
热议问题