2017-03-28 6 views
0

これはメインオーダーテーブルがどのように見えるかです: -コレクション番号は上部と下部がある注文番号を取得するには?

| Order_num | Collection_Num | 
+--------------+----------------+ 
| 20143045585 | 123456  | 
| 20143045585 | 789012  | 
| 20143045585 | 456897  | 
| 20143758257 | 546465  | 
+--------------+----------------+ 

これらのコレクションである: -

| tops  |  bottom | 
+--------------+----------------+ 
| 353735  | 745758  | 
| 123456  | 789012  | 
| 456456  | 456897  | 
| 323456  | 546465  | 
+--------------+----------------+ 

所望の出力は: - ここに

| Order_num | 
+--------------+ 
| 20143045585 | 

注文番号20143045585があり、両方の表番号2の同じ行の上部と下部(2番目の表の各行は、 'A Collection'と呼ばれる特定の組み合わせ、つまり1つの上部および対応する下部を形成します)。 私が知りたいこと - 'Collection_num'列の上端と下端を持つすべての注文番号。 誰かがこれのためのSQLコードで私を助けることができますか?

これが不明な場合は教えてください。

+1

は、サンプル出力を提供しますか? – Rams

+0

コレクションデータを特定するには、何らかの方法が必要です。これらの行には一意の値が必要です。 353735と745758が不必要な回転を伴わずに同じ行であるかどうかを知る方法はありません。 –

+0

サンプル出力 - | Order_Num | | 20143045585 | そのオーダーは同じコレクションのトップとボトムを支払っているので – Donny7

答えて

0
select Order_num 
From table_1 as A 
where exists 
(select tops from table_2 as B where B.tops = A.Collection_num) 
AND 
(select bottom from table2 as B where B.bottom = A.Collection_num) 
0

私はデータの最初のテーブルを持っていると仮定しており、各注文には2つ以下の関連するコレクションしかないとします。おそらく:

select T1.Order_Num 
     ,T1.Collection_Num AS Tops 
     ,T2.Collection_Num AS Bottom 
from Table1 T1 
inner join Table1 T2 
    on T1.Order_Num = T2.Order_Num 
    and T1.Collection_Num < T2.Collection_Num 
order by T1.Order_Num 
0

あなたはこのような何かがあなたのために働く必要があることをかなり確信してサブクエリ

select distinct order_num from #yourorder where collection_num 
    in (select tops from #yourcollections) 
    and order_num in 
    (select order_num from #yourorder where collection_num in 
     (select bottom from #yourcollections)) 
0

を使用して試すことができます。私はちょうどここにctesを使用して、テストデータを作成して照会できるようにしています。ここで

with Orders (OrderNum, CollectionNum) as 
(
    select 20143045585, 123456 union all 
    select 20143045585, 789012 union all 
    select 20143045585, 456897 union all 
    select 20143758257, 546465 
) 
, Collections (CollectionID, tops, bottoms) as 
(
    select 1, 353735, 745758 union all 
    select 2, 123456, 789012 union all 
    select 3, 456456, 456897 union all 
    select 4, 323456, 546465 
) 

select o.OrderNum 
    , t.tops 
    , b.bottoms 
from Orders o 
join Collections t on t.tops = o.CollectionNum 
join 
(
    select o.OrderNum 
     , b.bottoms 
     , b.CollectionID 
    from Orders o 
    join Collections b on b.bottoms = o.CollectionNum 
) b on b.CollectionID = t.CollectionID 
0

は、私が使用したクエリです:

Select * 
From (select A.Order_num, B.Coll_ID, B.Bottoms from Orders_table as A 
     Join Collections_Table as B 
     on A.Collection_num = B.Bottoms 
     ) as C 
    join 
     (select K.Order_num, M.Coll_ID, M.Tops from Orders_table as K 
     Join Collections_Table as M 
     on A.Collection_num = B.Tops 
     ) as D 
    on C.Orders_B = D.Orders_Num AND C.Coll_ID = D.Coll_ID 
)