MySQL return first and last record for consecutive identical results

依然范特西╮ 提交于 2019-12-01 21:35:47

The easiest way to approach this is using variables and I think the easiest approach is to add two variables, one the number of "up"s and the other the number of "down"s up to any given row. A given sequence of ups has a constant value for the number of preceding "down"s, and vice versa. This logic can be used for aggregation.

The resulting query is:

select result, min(time_stamp) as start_time, max(time_stamp) as end_time
from (select r.*,
             (@ups := @ups + (result = 'up')) as ups,
             (@downs := @downs + (result = 'down')) as downs
      from results r cross join
           (select @ups := 0, @downs := 0) vars
      where service_id = 1
      order by time_stamp
     ) r
group by result, (case when result = 'up' then downs else ups end);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!