Solved

Equivalent MySQL group_concat in SQL Server

Posted on 2015-02-22
2
411 Views
Last Modified: 2015-02-23
Hi,
My table looks like this:
Field1      Field2
1              A
1              B
1              C
2              A
2              B
With this mysql command select field1, group_concat(field2) as field2 from t1 Group by field1, I could achieve this:
Field1   Field2
1            A,B,C
2            A,B
How can I achieve this SQL Server 2008 R2
Regards
0
Comment
Question by:Omer-Pitou
2 Comments
 
LVL 18

Expert Comment

by:Simon
ID: 40624537
It can be done in MSSQL with a little more effort, using a recursive CTE (common table expression). The code below was originally written by Quassnoi and posted on his ExplainExtended.com blog
WITH
        qs(Field1,Field2, rn, cnt) AS
        (
        SELECT  Field1,Field2,
                ROW_NUMBER() OVER (PARTITION BY Field1 ORDER BY Field2),
                COUNT(*) OVER (PARTITION BY Field1)
        FROM    Table1
        ),
        t (Field1,Field2, gc, rn, cnt) AS
        (
        SELECT  Field1,Field2,
                CAST(Field2 AS NVARCHAR(MAX)), rn, cnt
        FROM    qs
        WHERE   rn = 1
        UNION ALL
        SELECT  qs.Field1, qs.Field2,
                CAST(t.gc + ', ' + qs.Field2 AS NVARCHAR(MAX)),
                qs.rn, qs.cnt
        FROM    t
        JOIN    qs
        ON      qs.Field1 = t.Field1
                AND qs.rn = t.rn + 1
        )
SELECT  Field1, gc as Field2
FROM    t
WHERE   rn = cnt
order by Field1
OPTION (MAXRECURSION 0)

Open in new window


See it working here on SQL Fiddle
0
 
LVL 48

Accepted Solution

by:
PortletPaul earned 500 total points
ID: 40625364
the T-SQL "FOR XML PATH" is the closest equivalent to group_concat() I believe

SELECT DISTINCT
      T1.Field1, CA.value
FROM Table1 T1
CROSS APPLY (
           SELECT
              STUFF(
                    (
                    SELECT
                          ', ' + T2.Field2
                    FROM Table1 AS T2
                    WHERE T2.Field1 = T1.Field1
                    ORDER BY T2.Field2
                    FOR XML PATH ('')
                    )
                   , 1, 1, '')
           ) ca (value)
;

Open in new window

Lines 7 to 14 relate to FOR XML PATH
Lines 5, 6 & 15 related to STUFF() which is simply used here to remove the first comma in the concatenated string
Note the use of CROSS APPLY which allows correlated subqueries into the FROM clause

see a demo here: http://sqlfiddle.com/#!3/5358b/3 
execution plan:  http://sqlfiddle.com/#!3/5358b/3/0



details
**MS SQL Server 2008 Schema Setup**:

    
    CREATE TABLE Table1
    	([Field1] int, [Field2] varchar(1))
    ;
    	
    INSERT INTO Table1
    	([Field1], [Field2])
    VALUES
    	(1, 'A'),
    	(1, 'B'),
    	(1, 'C'),
    	(2, 'A'),
    	(2, 'B'),
        (3, 'Z'),
    	(3, 'Y'),
    	(3, 'T'),
        (3, 'S')
    ;

**Query 1**:

    SELECT DISTINCT
          T1.Field1, CA.value
    FROM Table1 T1
    CROSS APPLY (
               SELECT
                  STUFF(
                        (
                        SELECT
                              ', ' + T2.Field2
                        FROM Table1 AS T2
                        WHERE T2.Field1 = T1.Field1
                        ORDER BY T2.Field2
                        FOR XML PATH ('')
                        )
                       , 1, 1, '')
               ) ca (value)
    

**[Results][2]**:
    
    | FIELD1 |       VALUE |
    |--------|-------------|
    |      1 |     A, B, C |
    |      2 |        A, B |
    |      3 |  S, T, Y, Z |



  [1]: http://sqlfiddle.com/#!3/5358b/3

  [2]: http://sqlfiddle.com/#!3/5358b/3/0

Open in new window

0

Featured Post

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
t-sql Joining Issue 10 40
SSIS with VPN COnnection 2 77
SQL - Update field defined as Text 6 17
Help to build a Proc... 6 21
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question