4

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

<timestamp> <state (A or B)>

我希望能够选择系列从状态 A 转换到状态 B 的所有时间(即 X t = B && 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 来解决这个问题?

4

2 回答 2

3

单一时间序列

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 已经提供了一些链接。

多个时间序列

...由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;
于 2013-10-10T23:18:51.477 回答
1

您需要使用领先或滞后窗口功能:

http://www.postgresql.org/docs/current/static/tutorial-window.html

http://www.postgresql.org/docs/current/static/functions-window.html

于 2013-10-10T23:16:52.817 回答