考虑以下数据
test1=# select * from sample order by created_at DESC;
id | status | service | created_at
----+--------+---------+---------------------
8 | OK | 1 | 2015-09-16 11:54:00
7 | OK | 1 | 2015-09-16 11:53:00
6 | FAIL | 1 | 2015-09-16 11:52:00
5 | OK | 1 | 2015-09-16 11:51:00
如何只选择ID为7和8的行。使用窗口函数我可以获取分区状态的行号,但到目前为止还没有找到如何将结果仅限制为标识为“成功”的最后行的方法给定service
的期间。
答案 0 :(得分:1)
最简单的方法是:
SELECT *
FROM sample AS s
LEFT JOIN (SELECT service, max(id)
FROM sample
WHERE status = 'FAIL'
GROUP BY service) AS q
ON s.id > q.id
AND s.service = q.service
答案 1 :(得分:1)
您需要为每个status = 'FAIL'
找到最新service
的时间,然后选择最近的service
相同的记录:
SELECT *
FROM sample
LEFT JOIN (
SELECT service, max(created_at) AS last_fail
FROM sample
WHERE status = 'FAIL'
GROUP BY service) f USING (service)
WHERE created_at > last_fail
OR last_fail IS NULL; -- also show services without ever failing
这假设只有两个状态代码。如果还有其他内容,请在status = 'OK'
子句中添加WHERE
过滤器。