在Postgres中的数组字段上应用聚合函数?

时间:2013-09-23 15:01:27

标签: sql arrays postgresql

是否可以对integer []字段(或其他数字数组)中的所有值应用聚合(如avg(),stddev())?

CREATE TABLE widget
(
  measurement integer[]
);

insert into widget (measurement) values ( '{1, 2, 3}');

select avg(measurement::integer[]) from widget;

ERROR:  function avg(integer[]) does not exist
LINE 4: select avg(measurement::integer[]) from widget;
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

********** Error **********

ERROR: function avg(integer[]) does not exist
SQL state: 42883
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Character: 71

我可以通过将数组拆分成多行来解决这个问题,比如

select avg(m)::float from (select unnest(measurement) m from widget) q;

但不太优雅。

谢谢。

2 个答案:

答案 0 :(得分:1)

你可以像这样创建简单的函数:

create function array_avg(_data anyarray)
returns numeric
as
$$
    select avg(a)
    from unnest(_data) as a
$$ language sql;

并像这样查询

select avg(array_avg(measurement))
from widget;

或者你可以简单地做

select avg((select avg(a) from unnest(measurement) as a))
from widget;

<强> sql fiddle demo

答案 1 :(得分:0)

如果有人想知道如何在保留其他属性的情况下做到这一点而不进行分组,则横向联接可提供一种简单的解决方案:

select Point, High, Low, Average
    from GridPoint G
    join lateral (
        select Max(V) High, Min(V) Low, Avg(V) Average
            from Unnest(G.Values) V
    ) _ on true