質問

私は(私は変更できない)2つのSQLテーブル、親(私は以上の完全な設計コントロールを持っている)との子供を参加しようとしています。それは子レコードのidのCSVリストを含む、varchar列を持つように私は、親テーブルを変更しました。私は今、親ごとに選択返す1行を行うにはなりように、そしていくつかのカウンタが再び。子供(すなわち真の「状態」を持っているどのように多くの子供たち)。

私はもともと私は、XML文字列にCSVリストを変換する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