Question

Let's say I have a simple table of the form:

<timestamp> <state (A or B)>

I want to be able to select all the times when the series transitions from state A to state B (i.e. Xt = B && Xt-1 = A). For example, with the data:

00:00 A
00:01 A
00:02 B
00:03 B
00:04 B
00:05 B
00:06 A
00:07 B
00:08 B

I want to return 00:02 and 00:07.

Maybe I'm searching the wrong keywords, but I can't find any good examples of similar problems. How might I approach this with PostgreSQL?

Was it helpful?

Solution

Single time series

SELECT ts
FROM  (
   SELECT *, lag(state) OVER (ORDER BY ts) AS last_state
   FROM   tbl
   ) sub
WHERE  state = 'B'
AND    last_state = 'A'
ORDER  BY ts;          -- I assume you want ordered results

@Denis already provided some links.

Multiple time series

... identified by a timeseries_id (answer to comment):

SELECT timeseries_id, ts
FROM  (
   SELECT *, lag(state) OVER (PARTITION BY timeseries_id
                              ORDER BY ts) AS last_state
   FROM   tbl
   ) sub
WHERE  state = 'B'
AND    last_state = 'A'
ORDER  BY timeseries_id, ts;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top