0

This is my SQL Server table data

            id  Name
            1   Active
            2    On-Hold
            3   Closed
            4    Cancelled
            5   Active
            6   On-Hold
            7   Closed
            8   Cancelled
            9   Active
            10  On-Hold
            11  Closed
            12  Cancelled

How can I query the table so that the results look like:

        Name        Id 
        Active     1,5,9
        On-Hold    2,6,10
        Closed     3,7,11
        Cancelled  4,8,12  
vhadalgi
  • 7,027
  • 6
  • 38
  • 67
Heena Chhatrala
  • 242
  • 1
  • 8
  • 1
    possible duplicate of [sql server sub query with a comma separated resultset](http://stackoverflow.com/questions/8302337/sql-server-sub-query-with-a-comma-separated-resultset) – NickyvV Feb 27 '14 at 11:36

3 Answers3

2
drop table #t
create table #t(id int,name varchar(20))
insert into #t values(1,'Active'),
            (2,'On-Hold'),
            (3 ,'Closed'),
            (4,'Cancelled'),
            (5,'Active'),
            (6,'On-Hold'),
            (7,'Closed'),
            (8,'Cancelled'),
            (9,'Active'),
            (10,'On-Hold'),
            (11,'Closed'),
            (12,'Cancelled')

 select distinct name,
stuff(
(
 select ',' + cast(id as varchar(10)) from #t t1 where t1.name=t2.name for xml path(''),type).value('.','varchar(max)'),1,1,'') from #t t2

 group by t2.name,t2.id

#SEE DEMO

vhadalgi
  • 7,027
  • 6
  • 38
  • 67
1
SELECT
   t1.name,
   MemberList = substring((SELECT ( ', ' + CAST(id as varchar) )
                           FROM table t2
                           WHERE t1.name = t2.name
                           ORDER BY 
                              name
                           FOR XML PATH( '' )
                          ), 3, 1000 )FROM table t1
GROUP BY name
Ketan Panchal
  • 230
  • 1
  • 2
  • 9
0

Use XML PATH

SELECT distinct t1.Name, 
  SUBSTRING((
    SELECT ',' + cast(t2.Id as varchar(30))
    FROM Status t2
    WHERE t2.Name = t1.Name
    FOR XML PATH('')), 2, 1000000) as [Id List]
FROM Status t1

Just ensure you swap your real table name in

jenson-button-event
  • 18,101
  • 11
  • 89
  • 155
  • You have to decode, also, the XML reserved chars. Otherwise, these chars will remain encoded: ...for xml path(''), type).value('.', 'varchar(max)') (or nvarchar(max)). – vhadalgi Feb 27 '14 at 12:43