Postgres 9.3 计算与相对于行的时间戳的列匹配的行

Postgres 9.3 count rows matching a column relative to row's timestamp

我以前使用过 WINDOW 函数,但仅在处理具有固定 cadence/interval 的数据时使用。我可能在聚合中遗漏了一些简单的东西,但我从来没有遇到过我不按固定间隔工作的情况。

我有一个 table 任意时间戳的记录样本。一个样本只有在它是前一个样本的增量时才会被记录,并且由于大量条件,采样率完全不规则。 table很简单:

id (int) 
happened_at (timestamp)
sensor_id (int)
new_value (float)

我正在尝试构建一个查询,该查询将包含给定结果行的 happened_at 之前的所有样本的计数。所以给定一个超简单的 2 行样本数据集:

id|happened_at     |sensor_id| new_value
1 |2019-06-07:21:41|134679   | 123.331
2 |2019-06-07:19:00|134679   | 100.009

我希望结果集如下所示:

happened_at     |sensor_id | new_value | sample_count
2019-06-07:21:41|134679    |123.331    |2
2019-06-07:19:00|134679    |123.331    |1

我试过:

SELECT *,
       (SELECT count(sample_history.id) OVER (PARTITION BY score_history.sensor_id 
        ORDER BY sample_history.happened_at DESC))
FROM sensor_history
ORDER by happened_at DESC

而且该死的不行。

(SELECT count(*) 
FROM sample_history
WHERE sample_history.happened_at <= sample_timestamp)

非常感谢您的见解。

在使用 window 函数时去掉 SELECT (sub-query)。

SELECT *,
       count(*) OVER (PARTITION BY sensor_id ORDER BY happened_at DESC)
FROM sensor_history
ORDER BY happened_at DESC