代码之家  ›  专栏  ›  技术社区  ›  Nick

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

  •  0
  • Nick  · 技术社区  · 5 年前

    我以前使用过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)
    

    非常感谢您的洞察力。

    0 回复  |  直到 5 年前
        1
  •  1
  •   a_horse_with_no_name    5 年前

    使用window函数时,去掉select(子查询)。

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