Given a table with a column containing double precision[]
with a fixed/same size.
I am able to fetch an element wise aggregation for min and max:
select min(array_col) from table;
select max(array_col) from table;
The result should be again a double precision[]
of the same size. If I want to use avg()
or stddev()
I get an error message like:
function stddev(double precision[]) does not exists
The same happens for avg()
. Is there any work around?
2
Answers
Use
unnest()
to open up the array and work on its elements: demoThis will take an average of all elements of all arrays. To get a separate average for each array, differentiate them by primary key (or add some unique id using
row_number()over()
) and use agroup by
:Be aware that
min()
used the way you did doesn’t pick the least element in each array, or from all arrays combined, or the array with the least sum of values but rather selects the first array according to default array order – in this case it’s empty first, value of subsequent elements ascending,null
last. Similar applies tomax()
. To get the least/greatest element or sum of elements from all arrays, usemin()
/max()
like in the first example, or the second to get one from each array.Element wise part
If you don’t mind addressing by hand:
But you can also leave listing the subscripts to a
generate_series()
andarray_upper()
: demoYou can use
unnest
to unpack the array, then apply the aggregate function. Assuming all arrays have three elements, that could beA better data model would not store this as an array, but as three columns.