Tuesday, 1 July 2014

Get comma secreted values

create table your_table(City_Code int,Post_Code nvarchar(10),    Post_Code_Description  nvarchar(10))
insert into your_table values(100,'A1','ABC')
insert into your_table values(100,'C8','XYZ')
insert into your_table values(100,'Z3','MNO')
insert into your_table values(200,'D4','LMN')
insert into your_table values(300,'E3','IJK')
insert into your_table values(300,'B9','RST')



SELECT City_Code,
      Post_Code =
        STUFF((SELECT ', ' + Post_Code
           FROM your_table b
           WHERE b.City_Code = a.City_Code
          FOR XML PATH('')), 1, 2, '')
--,Post_Code_Description=
        STUFF((SELECT ', ' + Post_Code_Description
           FROM your_table b
          WHERE b.City_Code = a.City_Code
          FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY City_Code

No comments:

Post a Comment