This (grouping of continuous ranges) is called gaps-and-islands
problem and can be effectively solved by using analytic functions (specifically ROW_NUMBER()
) which MySQL still has no support for.
But you can emulate ROW_NUMBER()
with session variables in the following way
SELECT MIN(time) time, status
FROM
(
SELECT time, status,
@n := @n + 1 rnum,
@g := IF(status = @s, @g + 1, 1) rnum2,
@s := status
FROM table1 CROSS JOIN (SELECT @n := 0, @g := 0, @s := NULL) i
ORDER BY time
) q
GROUP BY rnum - rnum2
Output:
| TIME | STATUS | |------------|--------| | 1390836600 | 1 | | 1390836610 | 0 | | 1390836620 | 1 |
Here is a SQLFiddle demo