用PostgresQL实现降噪功能

Implementing noise cancellation function with PostgresSQL

在我的 PostgresSQL 数据库中,我有一个 table 列 id 和一个整数 value.

这些值包含需要清除的噪音。我想通过将 n(例如 5)个连续值传递给函数然后计算它们的中值(或平均值或类似值)来实现。因此,给定值为 4, 1, 3, 4, 4, 2, 5, 4, 6, 4 的记录,第一个输出将是前 5 个值的中值 (4, 1, 3, 4, 4),第二个输出将是前 5 个值的中值,偏移量为 1 (1, 3, 4, 4, 2),然后是偏移量 2,依此类推。

我想在这样的查询中使用该函数 SELECT id, value, noisless_value(value) FROM measurements。这对 Postgres 可行吗?还是应该在数据库之外执行此类计算?

不幸的是,Postgres 没有使用 window 函数计算 运行 中位数的简便方法。因此,以下使用横向连接处理平均值和中值:

select t.*, t2.*
from t cross join lateral
     (select avg(value) as avg_5, percentile_cont(0.5) within group (order by value) as median_5
      from (select t2.*
            from t t2
            where t2.id >= t.id
            order by t2.id asc
            limit 5
           ) t2
     ) t2;

我应该指出,使用 window 函数的平均值更简单:

select t.*,
       avg(value) over (order by id range between current row and 4 following) as avg_5
from t;

Here 是一个 db<>fiddle.