0

我正在尝试加入两个 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)
4

1 回答 1

0

通过更多的摆弄和谷歌搜索,我现在有了这个:

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

合理的 ?

谢谢。

于 2010-03-01T12:08:29.773 回答