我正在尝试加入两个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)
答案 0 :(得分: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
合理吗?
感谢。