Given a table where each row has a timestamp and some measurement, how can I get all of the intervals during which the measurement consecutively satisfies some condition?
Here's a SQLfiddle (not sure if there's a better site for that nowadays).
So in this case, I'd like to to get all of the durations during which status
is true. The starting point should be the first true point chronologically. The end point can be the first false point or the last true point, whichever is easier.
I looked to window functions first. I could come up with separate queries, one that obtained the starting points and one that produced the end points, but it felt like I was going about it the wrong way.
Best Answer
You could try along:
The sub-select is necessary as window functions are not allowed directly in the
WHERE
clause.See it in action: SQL Fiddle (Thanks for preparing the fiddle! ;-) )
Update
To get the duration actually listed, try
See it in action: SQL Fiddle
It starts off by identifying the consecutive ranges. In S4, the ranges end when status is TRUE for the last time respectively; in S6 when status changed to FALSE.
This could probably be condensed a little bit. But as window functions cannot be nested (directly) anyway…
Please comment, if and as this requires adjustment / further detail.