Presto equivalent of MySQL group_concat
Asked Answered
F

3

48

I'm new to Presto and looking to get the same functionality as the group_concat function in MySQL. Are the following two equivalent? If not, any suggestions for how I can recreate the group_concat functionality in Presto?

MySQL:

select 
  a,
  group_concat(b separator ',')
from table
group by a

Presto:

select 
  a,
  array_join(array_agg(b), ',')
from table
group by a

(Found this as a suggested Presto workaround here when searching group_concat functionality.)

Frig answered 23/5, 2017 at 18:23 Comment(0)
E
57

Try using this in place of group_concat in Presto ::

select 
  a,
  array_join(array_agg(b), ',')
from table
group by a
Etheridge answered 24/2, 2018 at 12:41 Comment(1)
For those who see an unexpected order in the aggregation, you can use array_agg(x ORDER BY y)Haskell
E
31

Also, if you're looking for unique values only – an equivalent to group_concat(distinct ... separator ', ') – try this:

array_join(array_distinct(array_agg(...)), ', ')
Erb answered 20/3, 2018 at 19:51 Comment(2)
I've found that (in this particular case of achieving distinct group_concat) using nested queries for manually taking DISTINCT values performs better than the array_distinct UDF. Not sure that this would be universally true thoughEye
You can simplify this to array_agg(distinct b) and leave off the array_distanct() partCrosscut
B
5

There's no function as of this answer, though the feature has been requested.

The closest equivalent is mentioned in your question.

WITH tmp AS (
SELECT 'hey' AS str1
UNION ALL
SELECT ' there'
)
SELECT array_join(array_agg(str1), ',', '') AS joined
FROM tmp
Byrann answered 20/6, 2017 at 18:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.