Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate arrays grouped by another column in Presto?

Tags:

sql

presto

trino

Is this possible in SQL (preferably Presto):

I want to reshape this table:

id, array
1, ['something']
1, ['something else']
2, ['something']

To this table:

id, array
1, ['something', 'something else']
2, ['something']
like image 644
bry888 Avatar asked Sep 25 '18 14:09

bry888


2 Answers

In Presto you can use array_agg. Assuming that on input, all your arrays are single-element, this would look like this:

select id, array_agg(array[0])
from ...
group by id;

If, however, your input arrays are not necessarily single-element, you can combine this with flatten, like this:

select id, flatten(array_agg(array))
from ...
group by id;
like image 163
Piotr Findeisen Avatar answered Oct 25 '22 21:10

Piotr Findeisen


If you want an array that shows the distinct items in the aggregated array then this should work:

select id, array_distinct(flatten(array_agg(array))) as array
from ...
group by id
like image 36
Andrew Avatar answered Oct 25 '22 22:10

Andrew