Group by Continuous Days in MySQL – How to Guide

group byMySQL

I have table where I am storing some sequential data that indicate occurrences of some event given day.

id     from_id        to_id   date
1      2              1       2014-08-01
2      2              1       2014-08-02

3      2              1       2014-08-04
4      2              1       2014-08-05
6      2              1       2014-08-06

Sometimes event hasn't got place. Then I would like to get min and max from every uninterrupted sequences of records by data. According to example data it should return

from_id        to_id   min            max
2              1       2014-08-01     2014-08-02
2              1       2014-08-04     2014-08-06

If I would do simple group by with min and max

Select from_id, to_id, min(date), max(date) from events group by from_id, to_id 

it would return

from_id        to_id   min            max
2              1       2014-08-01     2014-08-06

How can I do that in MySQL?

Best Answer

SELECT from_id,to_id,
  CONCAT_WS(' - ',
    MIN(dt),
    CASE WHEN MAX(dt)>MIN(dt) THEN MAX(dt) END
  ) As intervals
FROM (
  SELECT from_id,to_id,
    CASE WHEN dt=@last_ci+INTERVAL 1 DAY THEN @n ELSE @n:=@n+1 END AS g,
    @last_ci := dt As dt
  FROM
    t, (SELECT @n:=0) r
  ORDER BY
    dt
) s
GROUP BY
  g

FIDDLE