Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres GROUP BY integer arrays

My DB table in Postgres 9.3

| f1|f2 | f3
| 1 | 2 | {1,2,3}
| 1 | 3 | {4,5}

f1,f2 are integers f3 is integer[].

How can I get this:

SELECT f1, myfn(f3)
FROM dbTable
GROUP BY f1;

so that I get:

| 1 | {1,2,3,4,5}

Is there a similar function in Postgres like array_agg that concatenates arrays and creates a new array;

like image 614
Alexandros Avatar asked Aug 05 '14 20:08

Alexandros


Video Answer


1 Answers

SQL Fiddle

First unnest then aggregate

select f1, array_agg(f3) as f3
from (
    select f1, unnest(f3) as f3
    from dbtable
) s
group by f1

To avoid duplicates and for a sorted output (intarry extension must be installed):

select f1, sort(uniq(array_agg(f3))) as f3
from (
    select f1, unnest(f3) as f3
    from dbtable
) s
group by f1
like image 114
Clodoaldo Neto Avatar answered Oct 12 '22 10:10

Clodoaldo Neto