我以前使用过window函数,但仅在处理具有固定频率/间隔的数据时使用。我可能在聚合中缺少了一些简单的东西,但我从来没有遇到过这样的场景:我没有使用固定的时间间隔工作。
我有一张表格记录任意时间戳的样本。只有当样本与前一个样本呈增量,且由于大量条件,样本率完全不规则时,才能记录样本。这张桌子很简单:
id (int)
happened_at (timestamp)
sensor_id (int)
new_value (float)
我正在尝试构造一个查询,该查询将包含给定结果行发生之前所有样本的计数。因此,给定一个非常简单的两行示例数据集:
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)
非常感谢您的洞察力。