How to concatenate arrays grouped by another column in Presto?
Asked Answered
T

3

14

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']
Truthfunction answered 25/9, 2018 at 14:59 Comment(0)
O
20

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;
Origami answered 25/9, 2018 at 19:9 Comment(0)
A
4

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
Abstergent answered 7/6, 2021 at 22:49 Comment(0)
B
0

You can also do set_union if you only need distinct values

select id, set_union(array) as array
from ...
group by id
Belvabelvedere answered 31/7, 2023 at 17:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.