4

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;

しかし、エレガントではありません。

ありがとうございました。

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 に答える