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