Sql server 2008 T-SQL查询:平展表
我需要构建一个查询来解决以下情况: 父表:Sql server 2008 T-SQL查询:平展表,sql-server-2008,tsql,Sql Server 2008,Tsql,我需要构建一个查询来解决以下情况: 父表: 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 其中一个单亲可以链接到多个子项。然后,查询将给出以下结果:
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
其中一个单亲可以链接到多个子项。然后,查询将给出以下结果:
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个子项,此查询将起作用:
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
PIVOT
是为您的场景设计的
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
这是可能的,但是你怎么知道你只会有5个孩子呢?为什么您需要对这些规范化的数据进行非规范化处理?这些数据最初是以这种格式(电子表格)存在的,由另一个进程解析并插入到数据库中。我需要从数据库中提取插入的数据,并模拟原始文件的外观来创建新的电子表格,以便他们可以验证数据库中的所有内容是否正确。我最初在使其正常工作时遇到问题,但我缺少行号()的分区。很好用,谢谢!