【发布时间】:2013-09-28 13:08:13
【问题描述】:
是否可以对 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;
但它不那么优雅。
谢谢。
【问题讨论】:
-
您可以定义一个自定义聚合,它将与数组一起使用。或者创建一个简单的函数,将数组转换为单个聚合值并在此函数之上聚合。
标签: sql arrays postgresql