Accomplishing MYSQL's Group_Concat in SQL Server [duplicate]

拜拜、爱过 提交于 2019-12-01 04:25:46

This can be done using a two-step process.

First, you can use a Common Table Expression to perform the first concatenation of the name and candy. The first part uses a query:

;with cte as
(
  select id, name+';'+ candy UserCandy
  from table_test
)
select *
from cte

See Demo. This gives a result:

| ID |   USERCANDY |
--------------------
|  1 |    John;MMs |
|  1 | John;KitKat |

Once the initial concatenation is done, then 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 a result:

| ID |                     USERCANDY |
--------------------------------------
|  1 | -----John;MMs-----John;KitKat |
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!