Solved

T-SQL convert rows to comma-separated string, with a GROUP BY

Posted on 2014-07-29
3
4,474 Views
Last Modified: 2016-11-28
Hello my under-apprecitated SQL genius buddies..

I have a two-column SQL 2012 table (disguised to protect the innocent), one of which is a group name, and one is numbers
IF OBJECT_ID('tempdb..test') IS NOT NULL
   DROP TABLE #test
GO

CREATE TABLE #test (
   group_name varchar(10), 
   id int
)

insert into #test (group_name, ID) 
values 
   ('red', 101), ('red', 102), ('blue', 103), ('blue', 104), ('hazel', 105), ('mauve', 106),
   ('grape', 107), ('red', 108), ('blue', 109), ('purple', 110), ('grape', 111), ('red', 112)

Open in new window

I need to generate some T-SQL, using FOR XML PATH I think but am not sure, to group by the group_name column, and return all of the ID's as a comma-separated string, like...

group_name    id_list
red              101, 102, 108, 112
blue            103, 104, 109
hazel          105
mauve        106,
grape          107, 111
purple        110

Thanks in advance.
Jim
0
Comment
Question by:Jim Horn
3 Comments
 
LVL 34

Accepted Solution

by:
Brian Crowe earned 500 total points
ID: 40227603
SELECT DISTINCT group_name,
      STUFF(
      (
            SELECT ',' + CAST(id AS VARCHAR)
            FROM #test AS t2
            WHERE t2.group_name = t.group_name
            FOR XML PATH('')
      ), 1, 1, '') AS id_list
FROM #test AS t
0
 
LVL 65

Author Closing Comment

by:Jim Horn
ID: 40227615
Looks like a winner.  Thanks.
0
 

Expert Comment

by:Ashutosh` Pandey
ID: 41905225
Thanks...Its working Fine
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

747 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now