gpt4 book ai didi

sql-server-2008 - T-SQL 查询 : Flattening out a table

转载 作者:行者123 更新时间:2023-12-03 23:38:06 24 4
gpt4 key购买 nike

我需要构建一个查询来解决下面的这种情况:

父表:

ParentId  Name
1 Parent A
2 Parent B

子表:

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

单亲可以链接到多个 child 。然后查询将给出以下结果:

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

这在 MS SQL 2008 中是否可行?

最佳答案

假设您只需要列出 5 个 child ,则此查询将起作用:

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

关于sql-server-2008 - T-SQL 查询 : Flattening out a table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10180878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com