What is a good way to find gaps in a set of datespans?

前端 未结 3 1144
清酒与你
清酒与你 2021-01-18 19:38

What is a way to find gaps in a set of date spans?

For example, I have these date spans:

1/ 1/11 - 1/10/11  
1/13/11 - 1/15/11  
1/20/11 - 1/30/11
         


        
3条回答
  •  北荒
    北荒 (楼主)
    2021-01-18 20:21

    Assuming MySQL, something like this would work:

    select @olddate := null;
    
    select start_date, end_date, datediff(end_date, @olddate) as diff, @olddate:=enddate
    from table
    order by start_date asc, end_date asc
    having diff > 1;
    

    Basically: cache the previous row's end_date in the @olddate variable, and then do a diff on that "old" value with the currel enddate. THe having clause will return only the records where the difference between two rows is greater than a day.

    disclaimer: Haven't tested this, but the basic query construct should work.

提交回复
热议问题