2016-08-26 4 views
-1

以下の例で助けが必要な場合、この例は4つのテーブルを左外部結合に結合した結果です。 null値を取得しますが、私が本当に望むのは、c6の最後の高い値に基づいて各C6に対して1レコードを取得することです。別の列にある最後の一意の値に基づいて1レコードを選択する

C1 C2 C3 C4 C5 C6 
4 A MM 90 GT 798 
4 A MM 90 GT 625 
4 A MM 90 GT 354 
4 A MM 90 GT 547 
5 K EE 60 SV 213 
5 K EE 60 SV 235 
5 K EE 60 SV 236 
9 O WW 40 PE 456 
9 O WW 40 PE 487 
9 O WW 40 PE 982 

私が使っているクエリは、このようなものです:

SELECT distinct C1, C2, C3, C4,C5,C6 
 
\t --,row_number() OVER(partition by c6 ORDER BY c1 asc)  \t 
 
    FROM table1 n 
 
    left outer join table 2 j on j.cad = n.Cad and j.P = n.P and j.H = 'Name' 
 
    left outer join table 3 k on k.id = n.id 
 
    left outer join table 4 m on m.u = n.u and m.s = n.s and m.Cad = n.Cad and n.P = m.P 
 
where NOT EXISTS (SELECT 1 from table 5 v WHERE N.U=v.U and N.S=v.S 
 
         and N.Cad=v.Cad and N.P=v.P) and n.Cad is not null 
 
\t \t \t \t \t and C6 is not null

+0

期待どおりの結果はありますか?あなたの質問を完全に理解していません。 – sgeddes

答えて

1

以下のクエリを使用してみてください。

With cte_1 
    As( SELECT C1, C2, C3, C4,C5,C6 
     ,row_number() OVER(partition by c1,c2,c3,c4,c5 ORDER BY c6 desc) RNO 
     FROM table1 n 
     left outer join table 2 j on j.cad = n.Cad and j.P = n.P and j.H = 'Name' 
     left outer join table 3 k on k.id = n.id 
     left outer join table 4 m on m.u = n.u and m.s = n.s and m.Cad = n.Cad and n.P = m.P 
     where NOT EXISTS (SELECT 1 from table 5 v  WHERE N.U=v.U and N.S=v.S 
         and N.Cad=v.Cad and N.P=v.P) and n.Cad is not null 
         and C6 is not null) 

     SELECT C1, C2, C3, C4,C5,C6 FROM cte_1 
     WHERE RNO=1 
+0

あなたの応答をありがとう、私は提案されたクエリをテストし、元のクエリを共有するいくつかのシナリオに気づいた、別のを使用して、テーブル4に参加していないとrow_numberをコメントし、クエリが3621レコードをもたらしたテーブル4および/またはrow_numberの結合それは私に3418を持って来るか、私は同じ量を持っているが、なぜそれが起こったかもしれないあなたのクエリを使用する場合 – RARV

+0

私はあなたがC1、C2、C3、C4、 C5、C6があなたのテーブルに重複しているかもしれません。そして、フィルタ条件を適用するときにそれがなくなりました。RNO = 1 –

+0

RNO = 1をコメントするだけで、結合条件を満たすテーブルから完全なレコードを見ることができます。 –

関連する問題