Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine rows in Amazon Redshift [duplicate]

I am using Amazon redshift. How do I combine the result of the columns.

If the original rows are:

*ID   Name  Color
----------------
1   John   White
1   John   Black
2   Mark   Blue
2   Mark   Red*

the result should be:

*ID   Name  Color
----------------
1   John   White Black
2   Mark   Blue Red*
like image 577
Mark Lorenz Vidad Avatar asked Dec 13 '22 19:12

Mark Lorenz Vidad


1 Answers

Redshift provides a function LISTAGG() for what you need

SELECT id, name, LISTAGG(Color,' ') AS Colors
FROM yourtable
GROUP BY id, name

For each group in a query, the LISTAGG aggregate function orders the rows for that group according to the ORDER BY expression, then concatenates the values into a single string. http://docs.aws.amazon.com/redshift/latest/dg/r_LISTAGG.html

SELECT id, name
 , LISTAGG(Color,' ') WITHIN GROUP (ORDER BY name) AS Colors
FROM yourtable
GROUP BY id, name
like image 136
Paul Maxwell Avatar answered Dec 24 '22 21:12

Paul Maxwell