Find conflicted date intervals using SQL

前端 未结 5 1302
梦谈多话
梦谈多话 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:32

    This will give you the rows that are incorrect.

    Added ROW_NUMBER() as I didnt know if all entries where in order.

    -- Testdata
    declare @date datetime = '2011-01-17'
    
    ;with yourTable(itemID, startDate, endDate)
    as
    (
        SELECT  1,  NULL, @date
        UNION ALL
        SELECT  2,  dateadd(day, -1, @date),    DATEADD(day, 10, @date)
        UNION ALL
        SELECT  3,  DATEADD(day, 60, @date),    NULL
    )
    
    -- End testdata
    
    ,tmp
    as
    (
        select  *
                ,ROW_NUMBER() OVER(order by startDate) as rowno 
        from    yourTable
    )
    
    select  *
    from    tmp t1
    left join   tmp t2
        on t1.rowno = t2.rowno - 1
    where   t1.endDate > t2.startDate
    

    EDIT: As for the updated question:

    Just add a PARTITION BY clause to the ROW_NUMBER() query and alter the join.

    -- Testdata
    declare @date datetime = '2011-01-17'
    
    ;with yourTable(itemID, startDate, endDate, intervalID)
    as
    (
        SELECT  1,  NULL, @date, 1
        UNION ALL
        SELECT  2,  dateadd(day, 1, @date), DATEADD(day, 10, @date),1
        UNION ALL
        SELECT  3,  DATEADD(day, 60, @date),    NULL,   1
        UNION ALL
        SELECT  4,  NULL, @date, 2
        UNION ALL
        SELECT  5,  dateadd(day, -1, @date),    DATEADD(day, 10, @date),2
        UNION ALL
        SELECT  6,  DATEADD(day, 60, @date),    NULL,   2
    )
    
    -- End testdata
    
    ,tmp
    as
    (
        select  *
                ,ROW_NUMBER() OVER(partition by intervalID order by startDate) as rowno 
        from    yourTable
    )
    
    select  *
    from    tmp t1
    left join   tmp t2
        on t1.rowno = t2.rowno - 1
        and t1.intervalID = t2.intervalID
    where   t1.endDate > t2.startDate
    

提交回复
热议问题