Wednesday, 7 September 2011

SQL Server Query

Here are the test table in which there are two field

create table  test
(
name varchar(30),
id varchar(30)
)

insert into test values('A1')

name              id
A                  1
B                 2
C                  3
C                 4
A                   2
A                   3
-------------------------
and i want to result  like below

A     1, 2, 3
B     2
C     3, 4

below query will help u as a tonic
SELECT [name], STUFF((SELECT ', ' + [id]
                       FROM test  T2
                          WHERE T1.[name] = T2.[name]
                      Order By [id]
                FOR XML PATH('')),1,1,'') AS [Subject Books]
           FROM test T1
           GROUP BY [name]


-----------------------------
Hope this will help you
Thanks
Rohit Srivastava

No comments:

Post a Comment