4

是否可以对整数 [] 字段(或其他数字数组)中的所有值应用聚合(如 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;

但它不那么优雅。

谢谢你。

4

2 回答 2

5

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

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

于 2013-09-23T16:24:56.430 回答
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
于 2020-10-29T05:30:04.740 回答