Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/three.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql Postgres 9.3统计与行的时间戳相关的列匹配的行_Postgresql_Window Functions - Fatal编程技术网

Postgresql Postgres 9.3统计与行的时间戳相关的列匹配的行

Postgresql Postgres 9.3统计与行的时间戳相关的列匹配的行,postgresql,window-functions,Postgresql,Window Functions,我以前使用过窗口函数,但仅在处理具有固定节奏/间隔的数据时使用。我可能在聚合中遗漏了一些简单的东西,但我从未遇到过不使用固定间隔的情况 我有一个表记录了任意时间戳的样本。只有当一个样本与前一个样本成增量,且由于大量条件,样本率完全不规则时,才会记录该样本。表格非常简单: id (int) happened_at (timestamp) sensor_id (int) new_value (float) 我正在尝试构造一个查询,该查询将包含给定结果行发生之前所有样本的计数。因此,给定一个超简单

我以前使用过窗口函数,但仅在处理具有固定节奏/间隔的数据时使用。我可能在聚合中遗漏了一些简单的东西,但我从未遇到过不使用固定间隔的情况

我有一个表记录了任意时间戳的样本。只有当一个样本与前一个样本成增量,且由于大量条件,样本率完全不规则时,才会记录该样本。表格非常简单:

id (int) 
happened_at (timestamp)
sensor_id (int)
new_value (float)
我正在尝试构造一个查询,该查询将包含给定结果行发生之前所有样本的计数。因此,给定一个超简单的2行样本数据集:

id |发生在|传感器| id |新|值 1 |2019-06-07:21:41|134679 | 123.331 2 |2019-06-07:19:00|134679 | 100.009 我希望结果集如下所示:

发生在|传感器| id |新|值|样本|计数 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)

非常感谢您的见解。

在使用窗口功能时,不要使用选择子查询

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

需要注意的是,我似乎需要在ASC而不是DESC按顺序进行分区才能得到正确的计算结果。