-1

I have two tables

TableA has three fields
Id | FieldA | SomethingElse

TableB has three fields as well
Id | FieldA_FK | FieldB

We can join the tables on

TableA.FieldA = TableB.FieldA_FK

I would like to select values on both these tables in order to retrieve the following dataset:

TableA.Id, TableA.FieldA, TableA.SomethingElse, [Concatenation of TableB.FieldB]

To retrieve [Concatenation of TableB.FieldB], I know I can do

declare @result varchar(500);
set @result = '';
select @result = COALESCE(@result + ',', '')  + FieldB 
from TableB b 
join TableA a on a.FieldA = b.FieldA_FK
select @result

How can I get the result described above with the concatenation on one result row only?

Thanks in advance.

Examples of data:

TableA
1   A   something
2   B   somethingElse

TableB
1   A   Aa
2   A   Ab
3   A   Ac
4   B   Ba
5   B   Bb

I would like to retrieve

1   A   something       Aa, Ab, Ac
2   B   somethingElse   Ba, Bb
G. Abitbol
  • 189
  • 1
  • 1
  • 8

2 Answers2

2

You can use the FOR XML PATH command:

SELECT 
    TableA.Id, TableA.FieldA, TableA.SomethingElse,
    [Concatenation of TableB.FieldB] =
    (STUFF((SELECT CAST(', ' + TableB.FieldB AS VARCHAR(MAX)) 
            FROM TableB
            WHERE (TableA.FieldA = TableB.FieldA_FK) 
            FOR XML PATH ('')), 1, 2, '')) 
FROM TableA 

Demo

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
1

This isn't as obvious as it should be, but you can abuse SQL's XML methods:

select a.ID, a.FieldA, a.FieldB
, stuff(
   (select ', ' + TableB.FieldB
   from TableB 
   inner join TableA on TableB.TableA_FK = TableA.ID
   for xml path(''), type
   ).value('(./text())[1]', 'varchar(max)')
   , 1,2,'')
from TableA a

See this fiddle: http://sqlfiddle.com/#!3/0fdd52/5

cjb110
  • 1,310
  • 14
  • 30