2017-12-22 14 views
-1

私は2つのテーブルを持っています。 1つはparent_Work_ordersを持ち、もう1つはchild_work_orderを持つ。それらはWO#によってリンクされています。両方のテーブルに値 '1'(アクティブ)または '0'(アクティブではない)を持つステータス列があります。今度は、parent_WOが閉じられ(アクティブではない)、そのWOの子がアクティブである可能性があります。制限付きグループ化

次のような方法でグループ化します。 1.親がアクティブな場合は、すべてのchild_WOを表示し、parent_WOをグループのヘッダーにします。 2.親がアクティブではなく、child_WOの1つがアクティブな場合は、その親に接続されているすべてのWOを再び表示します(アクティブかどうか)。 3.親が閉じていて、chid_WOも閉じている場合は表示しないでください。

PARENT TABLE

WO part status duedate 
1 abc 0  1/2/2018 
2 abc 1  1/2/2018 
3 abc 0  1/2/2018 

子テーブル

WO part status duedate 
1 abc 1  1/2/2018 
1 aaa 0  1/2/2018 
2 abc 0  1/2/2018 
2 abc 0  1/2/2018 
3 abc 0  1/2/2018 
3 qqq 0  1/2/2018 

私は唯一の私は制限付きでテーブルを結合するときWOS 1及び2は、表示したいです。これは可能ですか?

OUTOUT

WO part status duedate 
1 abc 0  1/2/2018 
1 abc 1  1/2/2018 
1 aaa 0  1/2/2018 
2 abc 1  1/2/2018 
2 abc 0  1/2/2018 
2 abc 0  1/2/2018 
+0

出力はどのように表示されますか? –

+0

@VamsiPrabhala申し訳ありませんが出力テーブルを追加しました。 WO "1"ではアクティブな1つの子が表示され、2には親がアクティブであるため、 –

答えて

1

すべての作業指示は、親と子テーブルから行を取得するためにそれを使用し、その後cteであなたの基準を満たすと、取得します。

with all_wos as (select wo 
       from child 
       group by wo 
       having max(status)=1 
       union all 
       select wo from parent where status=1 
       ) 
select p.*,1 as col 
from parent p 
where wo in (select wo from all_wos) 
union all 
select c.*,2 as col 
from child 
where wo in (select wo from all_wos) 
order by col,status,duedate 
1

Vamsiのソリューションに加えて、あなたもWHERE EXISTS(any row with this WO where Status=1 in either table)

0

することができますUNION 2台を持っているSELECTでこれを解決し、少なくともstatus = 1を持つすべてのWOSを選択することができます。 parent_WOは、あなたがそれによって余分な優先順位列と並べ替えを使用することができますグループ

のヘッダであること

;with temp as 
(
    select *, 1 as ObjPriority from @Parent 
    UNION ALL 
    select *, 2 as ObjPriority from @Child 
) 
select * from temp 
where WO IN (select distinct WO from temp where status = 1) -- at least status = 1 
order by ObjPriority -- parent is header