Diego
Diego

Reputation: 36136

Get child records on one column

I have a table parent and a table son like this:

Parent
ID   Name
1    Parent1
2    Parent2

Son
ID   ParentID
10      1
20      1
30      1
15      2
25      2

what's the easiest way to, when selecting the parent, get all the ID's of the sons on a single column? Like this:

Result:
ID   Name      AllMySons
1    Parent1   10,20,30
2    Parent2   15, 25

I thought of building a function to generate the string with the sons but does anyone have a better idea?

Upvotes: 3

Views: 1767

Answers (2)

Vishwanath Dalvi
Vishwanath Dalvi

Reputation: 36591

How about this.

SELECT p1.id,
       p1.name,
       AllMySons = Replace ((SELECT s.id AS 'data()'
                             FROM   son s
                             WHERE  p1.id = s.parentid
                             FOR xml path('')), ' ', ', ')
FROM   parent p1
GROUP  BY p1.id,
          p1.name;  

Upvotes: 1

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

select P.ID,
       P.Name,
       stuff((select ','+cast(S.ID as varchar(10))
              from Son S
              where S.ParentID = P.ID
              for xml path('')), 1, 1, '') AllMySons
from Parent P

SE-Data

Upvotes: 5

Related Questions