GROUP BY to combine/concat a column

viv_acious picture viv_acious · Mar 1, 2013 · Viewed 205.4k times · Source

I have a table as follow:

ID  User  Activity  PageURL  
 1  Me    act1      ab     
 2  Me    act1      cd     
 3  You   act2      xy     
 4  You   act2      st

I want to group by User and Activity such that I end up with something like:

User  Activity  PageURL  
Me    act1      ab, cd     
You   act2      xy, st

As you can see, the column PageURL is combined together separated by a comma based on the group by.

Would really appreciate any pointers and advice.

Answer

John Woo picture John Woo · Mar 1, 2013
SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity