T-SQL query: table alignment

I need to create a query to solve this scenario below:

ParentTable:

ParentId  Name
1         Parent A
2         Parent B

ChildTable:

ChildId   ParentId  Name 
10        1         Child X
11        1         Child Y
12        1         Child Z
13        2         Child Q

If one parent can be associated with several children. Then the query will give the following result:

Parent Name    1st-Child   2nd-Child   3rd-Child  4th-Child  5th-Child  
Parent A       Child X     Child Y     Child Z
Parent B       Child Q

Is this possible in MS SQL 2008?

+3
source share
2 answers

Assuming you only need to list 5 children, this query will work:

with T as (
    select P.Name as ParentName,
           C.Name as ChildName,
           row_number() over (partition by P.ParentId order by C.ChildId) as N
    from ParentTable P join ChildTable C on P.ParentId = C.ParentId
) 
select ParentName,
    max(case when N = 1 then ChildName else '' end) as '1st-child',
    max(case when N = 2 then ChildName else '' end) as '2nd-child',
    max(case when N = 3 then ChildName else '' end) as '3rd-child',
    max(case when N = 4 then ChildName else '' end) as '4th-child',
    max(case when N = 5 then ChildName else '' end) as '5th-child'
from T
group by ParentName
+6
source

PIVOT was designed for your scenario.

SELECT * FROM
(
    SELECT [Parent] = P.Name,
        [Child] = C.Name, 
        [Field] = 'Child ' + LTRIM(STR(
        ROW_NUMBER() OVER (PARTITION BY C.ParentId ORDER BY C.ChildId)))
    FROM ChildTable C
    JOIN ParentTable P ON P.ParentId = C.ParentId
) A
PIVOT (MAX([Child])
       FOR [Field] IN ([Child 1], [Child 2], [Child 3], [Child 4], [Child 5])) B
+3
source

All Articles