Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't aggregate arrays

I can create an array of arrays:

select array[array[1, 2], array[3, 4]];
     array     
---------------
 {{1,2},{3,4}}

But I can't aggregated arrays:

select array_agg(array[c1, c2])
from (
    values (1, 2), (3, 4)
) s(c1, c2);
ERROR:  could not find array type for data type integer[]

What am I missing?

like image 473
Clodoaldo Neto Avatar asked Apr 11 '13 11:04

Clodoaldo Neto


1 Answers

I use:

CREATE AGGREGATE array_agg_mult(anyarray) (
    SFUNC = array_cat,
    STYPE = anyarray,
    INITCOND = '{}'
);

and queries like:

SELECT array_agg_mult( ARRAY[[x,x]] ) FROM generate_series(1,10) x;

Note that you must aggregate 2-dimensional arrays, so you'll often want to wrap an input array in a single-element ARRAY[array_to_aggregate] array constructor.

like image 198
Craig Ringer Avatar answered Oct 02 '22 07:10

Craig Ringer