This can be done using a two-step process.
First, you can use Common Table Expression to perform the first concatenation of name and candy . The first part uses the query:
;with cte as ( select id, name+';'+ candy UserCandy from table_test ) select * from cte
See Demo . This gives the result:
| ID | USERCANDY | -------------------- | 1 | John;MMs | | 1 | John;KitKat |
Once the initial concatenation is done, you can use FOR XML PATH and STUFF to get the final result:
;with cte as ( select id, name+';'+ candy UserCandy from table_test ) select distinct c.id, STUFF( (SELECT '-----' + c2.UserCandy FROM cte c2 where c.id = c2.id FOR XML PATH ('')) , 1, 0, '') AS UserCandy from cte c;
See SQL Fiddle with Demo . This gives the result:
| ID | USERCANDY | -------------------------------------- | 1 | -----John;MMs-----John;KitKat |
Taryn
source share