我试图连接两个SQL表,父母(我有过完整的设计控制)和孩子(我不能改变)。我已经改变了父表,以便它有一个VARCHAR列,其中包含的子记录的ID的CSV列表。我现在想办一个选择返回一行每父,有的柜台重新。孩子们(即有多少孩子有一个真正的“状态”)。

我原本以为我可以在CSV列表转换成XML字符串,将它转换为XML类型的列,并使用XML“节点”加入子表 - 但我似乎无法得到语法右。

任何人都可以建议如何可以这样做?

谢谢, 罗斯

(这里就是我已经与玩弄)

declare @true bit; set @true = ~0
declare @false bit; set @false = 0
declare @parent table (id int, children varchar(max))
declare @child table (id int, status bit)

insert into @parent values (1,'1,2,3')
insert into @child values (1,@true)
insert into @child values (2,@false)
insert into @child values (3,@false)

;with parent as
(
select id as 'parentId', cast('<children><child id="' + replace (children,',','"/><child id="') + '"/></children>' as xml) as 'children' from @parent
)
select parentId, t2.child.query('.')
from parent
--join @child as child on (child.id = ??)
cross apply children.nodes('/children/child') as t2(child)
有帮助吗?

解决方案

通过多一点摆弄和谷歌搜索,我现在有这样的:

declare @true bit; set @true = ~0
declare @false bit; set @false = 0
declare @parent table (id int, children varchar(max))
declare @child table (id int, status bit)

insert into @parent values (1,'1,2,3')
insert into @child values (1,@true)
insert into @child values (2,@false)
insert into @child values (3,@false)
insert into @parent values (2,'4,5,6')
insert into @child values (4,@true)
insert into @child values (5,@false)
insert into @child values (6,@false)

;with parent as
(
select id as 'id', cast('<children><child id="' + replace(children,',','"/><child id="') + '"/></children>' as xml) as 'children' from @parent
)
select   parent.id
    ,count(child.id) as 'children'
    ,sum(case when child.status = @true then 1 else 0 end) as 'success'
    ,sum(case when child.status = @false then 1 else 0 end) as 'failed'
from parent
cross apply children.nodes('/children/child') as t2(child)
join @child as child on (child.id = t2.child.value('@id', 'int'))
group by parent.id

合理?

感谢。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top