1

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)
1
  • 3
    Hint: string_agg(). Commented Sep 27, 2018 at 20:35

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

This is great. Never heard of that function before and it works perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.