0

I'm having a bit of trouble implementing the XML PATH method of concatenating multiple rows. So, given the following table, Test.

ID  Type  
 1  boy
 2  boy
 3  boy
 1  girl
 2  girl
 3  man
 3  woman

The query is:

SELECT DISTINCT a.ID,
    (
        SELECT  b.Type + ','
        FROM Test as b
        WHERE a.Type = b.Type
        for XML PATH ('')
    )
FROM Test as a

but instead of returning:

ID  Type  
 1  boy,girl,man,
 2  boy,girl,
 3  boy,girl,woman

it instead returns this:

ID  Type
 1  boy,boy,boy,
 1  girl,girl,
 2  boy,boy,boy,
 2  girl,girl,
 3  boy,boy,boy,
 3  man,
 3  woman,

What's going on?

2 Answers 2

1

You're joining on the wrong field.

Try

SELECT DISTINCT a.ID,
    (
        SELECT  b.Type + ','
        FROM Test as b
        WHERE a.ID = b.ID
        for XML PATH ('')
    )
FROM Test as a
Sign up to request clarification or add additional context in comments.

1 Comment

Indeed I am! Thank you.
1

Instead of using DISTINCT prefer using GROUP BY something like this...

SELECT  a.ID,

   STUFF((SELECT  ', ' +  [Type] [text()]
          FROM Test 
          WHERE ID = a.[ID]
          for XML PATH (''),TYPE).
          value('.','NVARCHAR(MAX)'),1,2,'') AS [Type]

FROM Test as a
GROUP BY a.ID

1 Comment

@lunarplasma Yes certainly using group by instead of DISTINCT can give you much better performance.

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.