Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accomplishing MYSQL's Group_Concat in SQL Server [duplicate]

I'm porting an application I originally wrote to run on Apache using PHP and a MySQL database. One of the queries used the MySQL functions of Concat_WS and Group_Concat to first concatenate a few different columns into one string, and then concatenate all items that were grouped together by the Group_By clause.

As an example:

ID    Name    Candy
1     John    M&Ms
1     John    KitKat

The query:

Select Group_Concat(Concat_WS('-',Name, Candy) Separator '00--00') as UserCandy
From ExampleTable
Group By ID

The result:

UserCandy
John-M&Ms00--00John-KitKat

Now, I am trying to accomplish the same result in SQL Server 2008 using PHP 5.4+.

What I've tried:

SELECT Stuff(name + ';' + candy, 1, 0, '-----') AS UserCandy 
FROM   test 

The problem can be seen in the fiddle that I have setup.

The expected result would be:

-----John;MMs-----John;KitKat

Lastly, this becomes even more difficult when I add more columns to the mix. I want to merge the results (as shown above) where the ID is the same. This works very well with group_concat because it will automatically merge rows that have been grouped together.

like image 560
What have you tried Avatar asked Jun 18 '13 20:06

What have you tried


1 Answers

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 |
like image 164
Taryn Avatar answered Oct 08 '22 00:10

Taryn