Search code examples
sqlconcatenationamazon-athenastring-concatenation

How to concatenate multiple cell data into a single cell based on condition using SQL


New to using SQL here. I use Amazon Athena.

For example, say I have a table, customer_svc, of customers and the services they've subscribed to as follows:

customer service
Alex A
Alex B
Alex C
Dave A
Dave D

I need to design a query to concatenate the services for each unique customer into a single string as follows:

customer services
Alex A, B, C
Dave A, D

Any help would be much appreciated.


Solution

  • Tested in Amazon Athena / S3 :

    Dataset used for the query exmaple

    CSV data for example

    Query

    select customer, array_join(array_agg(service),',') as services from customer_svc group by customer
    

    Results

    Query results example

    Arrays documentation

    Amazon Athena Documentation