时间序列数据 - 查找状态转换的时间

时间:2013-10-10 22:53:38

标签: sql database postgresql time-series window-functions

假设我有一个简单的表格表格:

<timestamp> <state (A or B)>

我希望能够选择系列从状态A转换到状态B的所有时间(即X t = B&amp;&amp; X t-1 = A)。例如,使用数据:

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

我想要返回00:0200:07

也许我正在搜索错误的关键字,但我找不到类似问题的任何好例子。我如何使用PostgreSQL来解决这个问题?

2 个答案:

答案 0 :(得分:2)

单一时间序列

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.

多个时间序列

...由timeseries_id标识(回答评论):

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;

答案 1 :(得分:1)