Will
Will

Reputation: 989

SQL - Comma Separate Data When Using Group By

I'm using SQL Server and TSQL:

What I would like to do is comma separate values on one column when using a group by on another column. See data example below.

col1 --- col2

1121     abc
1123     aee
1335     afg
1121     def
1121     abc

I would like to Group By on "col1" and count the number of records, but I would also like to concatenate on col2 if the data is different. For instance, using value "1121" as a reference, see the data output below.

qty --- col1 --- col2

3       1121     abc, def
1       1123     aee
1       1335     afg

I thought of maybe using COALESCE, but I'm not sure how to implement it when using group by on another column.

Any help would be greatly appreciated.

Upvotes: 3

Views: 4259

Answers (1)

dcp
dcp

Reputation: 55444

Here's a complete, tested, working example.

create table tmp (col1 varchar(100), col2 varchar(100));
insert into tmp values ('1121',    'abc');
insert into tmp values ('1123',    'aee');
insert into tmp values ('1335',    'afg');
insert into tmp values ('1121',    'def');
insert into tmp values ('1121',    'abc');

SELECT 
distinct r.col1,
       STUFF((SELECT distinct ','+ a.col2
               FROM tmp a
             WHERE r.col1 = a.col1
            FOR XML PATH(''), TYPE).value('.','VARCHAR(max)'), 1, 1, ''),
       (select COUNT(*) cnt from tmp a where r.col1 = a.col1) cnt
 FROM tmp r

Result

1121    abc,def 3
1123    aee     1
1335    afg     1

References: Used OMG Ponies' answer here as a guide.

Upvotes: 5

Related Questions