[英]Select until row matches in Postgres
給定以下數據結構:
id | subscription_id | state | created_at | ok
---------+-----------------+-------+----------------------------+----
1 | 1 | error | 2015-06-30 15:20:03.041045 | f
2 | 1 | error | 2015-06-30 15:20:04.582907 | f
3 | 1 | sent | 2015-06-30 22:50:04.50478 | f
4 | 1 | error | 2015-06-30 22:50:06.067279 | f
5 | 1 | error | 2015-07-01 22:50:02.356113 | f
我想使用state='error'
檢索最后一條消息,直到該state
包含其他內容。
它應該返回以下內容:
id | subscription_id | state | created_at | ok
---------+-----------------+-------+----------------------------+----
4 | 1 | error | 2015-06-30 22:50:06.067279 | f
5 | 1 | error | 2015-07-01 22:50:02.356113 | f
在回答了這個問題以及之后的 問題 之后 ,我最終在下面得到了這個查詢:
SELECT * from (select id, subscription_id, state, created_at,
bool_and(state='error')
OVER (PARTITION BY state order by created_at, id) AS ok
FROM messages ORDER by created_at) m2
WHERE subscription_id = 1;
但是,考慮到我添加了PARTITION BY state
,查詢只是忽略了所有不包含error
state
,而是顯示了以下內容:
id | subscription_id | state | created_at | ok
---------+-----------------+-------+----------------------------+----
1 | 1 | error | 2015-06-30 15:20:03.041045 | f
2 | 1 | error | 2015-06-30 15:20:04.582907 | f
4 | 1 | error | 2015-06-30 22:50:06.067279 | f
5 | 1 | error | 2015-07-01 22:50:02.356113 | f
在找到其他狀態並按照頂部僅描述ID 4和5的示例進行匹配之后,應如何進行查詢以“停止”?
如果我正確理解,則需要這樣做:
select * from messages
where
id > (select coalesce(max(id), 0) from messages where state <> 'error')
and
subscription_id = 1
假設id
是唯一的(PK?)列,而更高的id表示最新記錄。
編輯
沒錯,就像@Marth提到的那樣,可能您需要在子查詢中添加... AND subscription_id = 1
不需要進入PARTITION BY state
,您想要SELECT
之后所有行都是error
行(按created_at ASC
順序),即bool_and(state = 'error')
為true
:
SELECT * FROM (
SELECT *,
bool_and(state = 'error') OVER (ORDER BY created_at DESC, id) AS only_errors_afterward
FROM sub
) s
WHERE only_errors_afterward
;
┌────┬─────────────────┬───────┬───────────────────────────────┬────┬───────────────────────┐
│ id │ subscription_id │ state │ created_at │ ok │ only_errors_afterward │
├────┼─────────────────┼───────┼───────────────────────────────┼────┼───────────────────────┤
│ 5 │ 1 │ error │ 2015-07-01 22:50:02.356113+02 │ f │ t │
│ 4 │ 1 │ error │ 2015-06-30 22:50:06.067279+02 │ f │ t │
└────┴─────────────────┴───────┴───────────────────────────────┴────┴───────────────────────┘
(2 rows)
編輯:根據預期結果,您可能需要在window函數中使用PARTITION BY subscription_id
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.