SELECT grp, min(date) AS start, max(date) AS stop FROM ( SELECT date, speed, count(is_reset) OVER () AS grp FROM ( SELECT date, speed, CASE WHEN overspeed <> lag(overspeed) OVER (ORDER BY date) THEN 1 END AS is_reset FROM ( select fecha as date,velocidad as speed, velocidad>100 as overspeed from reports.avl_historico_354898046636089 where fecha between '2017-04-19 00:00:00-03' and '2017-04-20 00:00:00-03' and velocidad>2 and ignicion=1 order by fecha ) AS t ) AS t2 ) AS t3 GROUP BY grp; SELECT grp, min(date) AS start, max(date) AS stop FROM ( SELECT date, speed, count(is_reset) OVER () AS grp FROM ( SELECT date, speed, CASE WHEN overspeed <> lag(overspeed) THEN 1 END AS is_reset FROM ( select fecha as date,velocidad as speed, velocidad>100 as overspeed from reports.avl_historico_354898046636089 where fecha between '2017-04-19 00:00:00-03' and '2017-04-20 00:00:00-03' and velocidad>2 and ignicion=1 order by fecha ) AS t ) AS t2 ) AS t3 GROUP BY grp; SELECT grp, min(date) AS start, max(date) AS stop FROM ( SELECT date, speed, count(is_reset) OVER () AS grp FROM ( SELECT date, speed, CASE WHEN overspeed <> lag(overspeed) OVER (ORDER BY date) THEN 1 END AS is_reset FROM ( select fecha as date,velocidad as speed, velocidad>100 as overspeed from reports.avl_historico_354898046636089 where fecha between '2017-04-19 00:00:00-03' and '2017-04-20 00:00:00-03' and velocidad>2 and ignicion=1 ) AS t ) AS t2 ) AS t3 GROUP BY grp; SELECT grp, min(date) AS start, max(date) AS stop FROM ( SELECT date, speed, count(is_reset) OVER () AS grp FROM ( SELECT date, speed, CASE WHEN overspeed <> lag(overspeed) THEN 1 END AS is_reset FROM ( select fecha as date,velocidad as speed, velocidad>100 as overspeed from reports.avl_historico_354898046636089 where fecha between '2017-04-19 00:00:00-03' and '2017-04-20 00:00:00-03' and velocidad>2 and ignicion=1 order by fecha ) AS t ) AS t2 ) AS t3 GROUP BY grp; lang-sql