0

親 (完全に設計を制御できる) と子 (変更できない) の 2 つの SQL テーブルを結合しようとしています。親テーブルを変更して、子レコードの ID の CSV リストを含む varchar 列を持つようにしました。親ごとに1行を返す選択を行い、いくつかのカウンターを返したいと思います。子 (つまり、true の「ステータス」を持つ子の数)。

私は当初、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 に答える