jackstraw22
jackstraw22

Reputation: 641

Combine multiple values into one cell in Postgres

I have a data set that can multiple rows with the same claim no. and different names:

   claim_id           name
    112               John Smith
    112               Tom Harris
    113               Randy Dugar

If the claim id is the same, then I need all the names to be in one row separated by a comma:

    claim_no          name
    112               John Smith, Tom Harris
    113               Randy Dugar

I've created something similar in T-SQL, but am new to Postgres. I've tried something like the following, but I just get an error:

   with firstrun as(
   select distinct kia.claim_id as claim_id,  c.first_name ||' '  
   ||c.last_name as name
   from kia
   inner join
   claims c
   on kia.claim_id = c.claim_id


   )

   select distinct claim_id, substring((Select ',' || ' '|| fr.name as   text()]
   from firstrun fr
   for xml path('')), 2, 500)

Upvotes: 1

Views: 2716

Answers (1)

Mureinik
Mureinik

Reputation: 310993

The string_agg aggregate function will do all the heavy lifting for you:

SELECT   claim_id, STRING_AGG(name, ', ')
FROM     claims
GROUP BY claim_id

Upvotes: 4

Related Questions