Postgres中的向量(数组)加法

Bra*_*ert 5 sql arrays postgresql vectorization

我有一列numeric[]都具有相同大小的值。我想对它们进行元素平均。我的意思是说

{1, 2, 3}, {-1, -2, -3}, and {3, 3, 3}
Run Code Online (Sandbox Code Playgroud)

应该是{1, 1, 1}。同样有趣的是如何对这些元素进行总和,尽管我希望一个解决方案将是另一个解决方案。

(NB: The length of the arrays is fixed within a single table, but may vary between tables. So I need a solution which doesn't assume a certain length.)

My initial guess is that I should be using unnest somehow, since unnest applied to a numeric[] column flattens out all the arrays. So I'd like to think that there's a nice way to use this with some sort of windowing function + group by to pick out the individual components of each array and sum them.

-- EXAMPLE DATA
CREATE TABLE A
  (vector numeric[])
;

INSERT INTO A
  VALUES
    ('{1, 2, 3}'::numeric[])
    ,('{-1, -2, -3}'::numeric[])
    ,('{3, 3, 3}'::numeric[])
;
Run Code Online (Sandbox Code Playgroud)

Pau*_*rth 5

我已经编写了一个扩展来使用快速 C 函数进行向量加法(以及减法、乘法、除法和幂)。你可以在 GithubPGXN找到它。

给定两个数组ab你可以说vec_add(a, b). 您还可以将任一侧添加到标量,例如vec_add(a, 5).

如果你想要一个SUM聚合函数,你可以在aggs_for_vecs 中找到它,也在PGXN 上

最后,如果要汇总单个数组的所有元素,可以使用aggs_for_arrays ( PGXN )。


And*_*eas 1

来自http://www.postgresql.org/message-id/4C2504A3.4090502@wp.pl

select avg(unnested) from (select unnest(vector) as unnested from A) temp;


编辑:我想我现在更好地理解了这个问题。

这是一个可能的解决方案:/sf/answers/613721531/我不认为它很优雅,也不确定它会表现良好:

测试数据:

CREATE TABLE A
  (vector numeric[], id serial)
;

INSERT INTO A
  VALUES
    ('{1, 2, 3}'::numeric[])
    ,('{4, 5, 6}'::numeric[])
    ,('{7, 8, 9}'::numeric[])
;
Run Code Online (Sandbox Code Playgroud)

询问:

select  avg(vector[temp.index])
from    A as a
join
    (select generate_subscripts(vector, 1) as index
              , id
        from    A) as temp on temp.id = a.id
group by temp.index
Run Code Online (Sandbox Code Playgroud)