[英]Selecting latest consecutive records that match a condition with PostgreSQL
I am looking for a PostgreSQL query to find the latest consecutive records that match a condition. 我正在寻找PostgreSQL查询来找到符合条件的最新连续记录。 Let me explain it better with an example:
让我用一个例子更好地解释一下:
| ID | HEATING STATE | DATE |
| ---- | --------------- | ---------- |
| 1 | ON | 2018-02-19 |
| 2 | ON | 2018-02-20 |
| 3 | OFF | 2018-02-20 |
| 4 | OFF | 2018-02-21 |
| 5 | ON | 2018-02-21 |
| 6 | OFF | 2018-02-21 |
| 7 | ON | 2018-02-22 |
| 8 | ON | 2018-02-22 |
| 9 | ON | 2018-02-22 |
| 10 | ON | 2018-02-23 |
I need to find all the recent consecutive records with date >= 2018-02-20 and heating_state ON, ie the ones with ID 7, 8, 9, 10. My main issue is with the fact that they must be consecutive . 我需要找到日期> = 2018-02-20和heating_state ON的所有最近连续记录,即ID为7、8、9、10的记录。我的主要问题是它们必须是连续的 。
For further clarification, if needed: 为了进一步说明,如果需要:
Use the LEAD
function with a CASE
expression. 将
LEAD
函数与CASE
表达式一起使用。
Query 1 : 查询1 :
SELECT id,
heating_state,
dt
FROM (SELECT t.*,
CASE
WHEN dt >= timestamp '2018-02-20'
AND heating_state = 'ON'
AND LEAD(heating_state, 1, heating_state)
OVER (
ORDER BY dt ) = 'ON' THEN 1
ELSE 0
END on_state
FROM t) s
WHERE on_state = 1
| id | heating_state | dt |
|----|---------------|----------------------|
| 7 | ON | 2018-02-22T00:00:00Z |
| 8 | ON | 2018-02-22T00:00:00Z |
| 9 | ON | 2018-02-22T00:00:00Z |
| 10 | ON | 2018-02-23T00:00:00Z |
I think this is best solved using windows functions and a filtered aggregate. 我认为最好使用Windows函数和筛选的聚合来解决。
For each row, add the number of later rows that have state = 'OFF'
, then use only the rows where that count is 0. 对于每一行,添加
state = 'OFF'
的以后的行数,然后仅使用计数为0的行。
You need a subquery because you cannot use a window function result in the WHERE
condition ( WHERE
is evaluated before window functions). 您需要一个子查询,因为您不能在
WHERE
条件下使用窗口函数结果(在窗口函数之前先评估WHERE
)。
SELECT id, state, date
FROM (SELECT id, state, date,
count(*) FILTER (WHERE state = 'OFF')
OVER (ORDER BY date DESC, state DESC) AS later_off_count
FROM tab) q
WHERE later_off_count = 0;
id | state | date
----+-------+------------
10 | ON | 2018-02-23
9 | ON | 2018-02-22
8 | ON | 2018-02-22
7 | ON | 2018-02-22
(4 rows)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.