0

My Question:

VALUES:      **TABLE A**

ID       Number      Code
ABC99       1         XYZ0
ABC99       1         XyZ1
ABC99       2         XZY2
ABC99       3         XYZ1
ABC99       3         XwZ4
DEF88       5         QPR1
DEF88       5         QPR2
DEF88       6         QPS1

Desired Out Put: ID should be distinct with Corresponding Number and Code Concatenated

OUTPUT:

ID        Number      Code
ABC99       1         XYZ0,XyZ1
ABC99       2         XZY2
ABC99       3         XYZ1,XwZ4
DEF88       5         QPR1,QPR2
DEF88       6         QPS1

The output: ID matches with a unique number and makes multiple rows (Code) to a single row separated with a comma (No matter how many they are).

Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
Louis
  • 19
  • 3
  • Duplicated: http://stackoverflow.com/questions/31211506/how-stuff-and-for-xml-path-work-in-sql-server – McNets Feb 07 '17 at 18:21

1 Answers1

0
declare @t table (
    ID varchar(10),
    Number int,
    Code varchar(10)
)

insert into @t values
('ABC99', 1, 'XYZ0'),
('ABC99', 1, 'XyZ1'),
('ABC99', 2, 'XZY2'),
('ABC99', 3, 'XYZ1'),
('ABC99', 3, 'XwZ4'),
('DEF88', 5, 'QPR1'),
('DEF88', 5, 'QPR2'),
('DEF88', 6, 'QPS1');


select
    ID, Number,
    stuff((select ',' + Code from @t b
            where a.ID = b.ID 
            and a.Number = b.Number
            for XML PATH('')
    ),1,1,'') Codes
from @t a
group by ID, Number;
Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76