Home > Software design >  Concatenate distinct values in a group by
Concatenate distinct values in a group by

Time:02-17

I have data like this:

Group   Provider
A       ABC
A       DEF
B       DEF
B       HIJ

And I want to transform the data like this:

Group ProviderList
A      ABC, DEF
B      DEF, HIJ

I was trying something like this using a concat(select distinct...) but not sure if this is the best approach

SELECT distinct
  group, 
  CONCAT(select distinct provider from data)
FROM data 
GROUP BY 1

CodePudding user response:

What Laurenz meant with string_agg() is the following

SELECT
  group, 
  STRING_AGG(Provider,',') as ProviderList
FROM data 
GROUP BY 1

Optionally you could also use:

STRING_AGG(provider,',' order by Provider)
  • Related