I've used this sample:
create table if not exists myt(id int, dd date);
insert into myt values
(1, '2017-01-01'),
(1, '2017-01-02'),
(1, '2017-01-03'),
(1, '2017-01-04'),
(1, '2017-01-08'),
(1, '2017-01-09'),
(1, '2017-01-10');
First you should set a partition by consecutive days:
select id, dd,
if(@last_date = '1900-01-01' or datediff(dd, @last_date) = -1, @cn := @cn, @cn := +1) consecutive,
@last_date := dd
from
(select @last_date := '1900-01-01', @cn := 0) x,
(select id, dd
from myt
order by dd desc) y
;
This returns:
+----+---------------------+-------------+
| id | dd | consecutive |
+----+---------------------+-------------+
| 1 | 10.01.2017 00:00:00 | 0 |
| 1 | 09.01.2017 00:00:00 | 0 |
| 1 | 08.01.2017 00:00:00 | 0 |
+----+---------------------+-------------+
| 1 | 04.01.2017 00:00:00 | 1 |
| 1 | 03.01.2017 00:00:00 | 1 |
| 1 | 02.01.2017 00:00:00 | 1 |
| 1 | 01.01.2017 00:00:00 | 1 |
+----+---------------------+-------------+
After you set a partition, then get MAX and MIN date for each partition:
select id, min(dd) as ini, max(dd) as fin, datediff(max(dd), min(dd)) as Days
from (
select id, dd,
if(@last_date = '1900-01-01' or datediff(dd, @last_date) = -1, @cn := @cn, @cn := +1) consecutive,
@last_date := dd
from
(select @last_date := '1900-01-01', @cn := 0) x,
(select id, dd
from myt
order by dd desc) y
) z
group by consecutive
;
Result:
+----+---------------------+---------------------+------+
| id | ini | fin | Days |
+----+---------------------+---------------------+------+
| 1 | 08.01.2017 00:00:00 | 10.01.2017 00:00:00 | 2 |
+----+---------------------+---------------------+------+
| 1 | 01.01.2017 00:00:00 | 04.01.2017 00:00:00 | 3 |
+----+---------------------+---------------------+------+
Check it: http://rextester.com/XMIX80360