Search code examples
sqlprestotrino

How to concatenate arrays grouped by another column in Presto?


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']

Solution

  • 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;