0

I'm having again a bit of trouble implementing the XML PATH method of concatenating multiple rows.

Given the following SQL Server temptable:

project    |    NAME    |      display_name
-----------+------------+-------------------
  a         Developer         Amelia     
  a         Developer         Ruby
  a         Administrator     Olivia     
  b         User              Isla    
  b         Developer         Emily   
  c         User              Poppy     
  c         Administrator     Ava    
  c         Administrator     James 

The result should be:

project    |    NAME        | display_name
-----------+----------------+----------------
  a         Developer         Amelia, Ruby
            Administrator     Olivia

  b         User              Isla    
            Developer         Emily   

  c         User              Poppy     
            Administrator     Ava,James

Is something like this even possible with XML PATH etc. ?

1
  • Your query is a simple case of the usual solution. Could you post it to see what's going wrong? Commented Nov 19, 2018 at 10:18

1 Answer 1

1

Yes you can use FOR XML PATH() clause :

SELECT DISTINCT t.project, t.name, STUFF(t1.display_name, 1, 1, '') AS display_name
FROM table t CROSS APPLY
     (SELECT ', '+t1.display_name 
      FROM table t1
      WHERE t1.project = t.project AND t1.name = t.name
      FOR XML PATH('')
     ) t1(display_name);
Sign up to request clarification or add additional context in comments.

1 Comment

I like your sintaxis of calling the subquery on a cross apply and removing the trailing , on the result. Much cleaner, I will use it.

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.