有没有办法在 PostgreSQL 上计算数值积分?

Is there a way of computing numerical integration on PostgreSQL?

我有一个 table,其中包含以下列:timestampnameactivePower。我想以此为基础计算功耗并将其添加到 Grafana 折线图中。

现在,我正在做的是累加和,如下所示:

SELECT
  "timestamp" as time,
  "name", sum("activePower")
    OVER(
      PARTITION BY "name"
      ORDER BY "timestamp"
    ) AS cumulative_sum
FROM   main

不幸的是timestamp的间隔不规则,我想做一些类似数值积分的事情(使用梯形法则什么的)。

您可以使用 lag() 和求和。像这样:

select m.*,
       sum( (extract(epoch from timestamp) - extract(epoch from prev_timestamp)) * (activePower + prev_activePower) / 2 ) as activePower_seconds
from (select m.*,
             lag(timestamp) over (partition by name order by timestamp) as prev_timestamp,
             lag(activePower) over (partition by name order by activePower) as prev_activePower
      from main m
     ) m;

横轴使用秒数进行积分。

虽然标记为正确,但第二行:

lag(activePower) over (partition by name order by activePower)

也应该按时间戳排序。