-1

I have a datetime columns, that are fromDate and toDate.

I am trying to figure out if the interval is continuos.

This is how my table looks this:

enter image description here

I would like to get the following results with 3 intervals:

fromDate            | toDate
2020-05-23 08:00:00 | 2020-05-23 09:15:00
2020-05-23 11:00:00 | 2020-05-23 12:00:00
2020-05-23 15:00:00 | 2020-05-23 15:30:00

Any idea how to do this?

GMB
  • 216,147
  • 25
  • 84
  • 135
Bob
  • 8,392
  • 12
  • 55
  • 96

1 Answers1

1

This is a gaps-and-islands problem, where you want to group together "adjacent" rows.

Here is one option using lag() to recover the todate on the previous row, and then a window sum() to identify the islands. The final step is to aggregate each island:

select min(fromdate) fromdate, max(todate) todate
from (
    select t.*, 
        sum(case when fromdate = lag_todate then 0 else 1 end) over(order by fromdate) grp
    from (
        select t.*, lag(todate) over(order by fromdate) lag_todate
        from mytable t
    ) t
) t
group by grp

Note: since you are running MySQL, we can simplify the expression in the window sum a little. This is shorter, and should work just fine:

sum(1 - fromdate <=> lag_todate) over(order by fromdate) grp
GMB
  • 216,147
  • 25
  • 84
  • 135