假设我有一个简单的表格表格:
<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:02
和00:07
。
也许我正在搜索错误的关键字,但我找不到类似问题的任何好例子。我如何使用PostgreSQL来解决这个问题?
答案 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)