MySQL return first and last record for consecutive identical results

前端 未结 1 1830
陌清茗
陌清茗 2021-01-20 13:27

I\'m using MySQL and have a table called \'results\' which stores the outcome of a monitor which determines whether a service is up or down at a specific time.



        
1条回答
  •  一生所求
    2021-01-20 13:46

    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);
    

    0 讨论(0)
提交回复
热议问题