2017-01-03 5 views
2

保護者がリストされていない場合は、連絡先テーブルから特定の顧客を選択しようとしています。1行が条件を満たす場合IDのすべての行を除外

ClientId | ContactId | Guardian 
123  | 1   | Y 
123  | 2   | N 
123  | 3   | N 

456  | 4   | N 
456  | 5   | N 
456  | 6   | N 

所望の出力:

ClientId | ContactId | Guardian 
456  | 4   | N 
456  | 5   | N 
456  | 6   | N 

だから私の目標は、クライアント456は、私のクエリ結果に表示さだろうが、私が書いた123 ないクライアントは、次のことです:

select * from Contacts 
where Guardian <> (case when Guardian = 'Y' 
    then Guardian 
     else '' 
     end) 

私はまた

select * from Contacts c 
where not exists (select 1 
        from Contacts c2 
        where c2.ContactId = c.ContactId 
        and c.Guardian = 'Y')      
を試してみました

しかし、Guardian = Yの行を除外し、Guardian = NのClientIdに関連付けられた行があってもClientIdが結果に表示されない。私は特定の値を持つ行だけを選択する方法を探していましたが、行の1つが一致した場合にClientIdを完全に除外する方法は見つけられません。

私は本当にありがとうと思います!

+0

を私たちにすでに提供されたデータのサンプルに対する所望の出力を示してください。 –

+0

@PM 77-1希望する出力は ClientId | ContactId |ガーディアン 456 | 4 | N 456 | 5 | N 456 | 6 | N – jfe042

+0

あなたの質問にこの情報を追加してください([編集]を使用して)。 –

答えて

0

サブクエリにはGuardian = 'Y'が含まれていないClientIdが取得されます。完全なレコードが必要な場合は、外部クエリも使用してください。あなただけのIDが必要な場合は、単にサブクエリ

select * 
from Contacts 
where ClientId in 
(
    select ClientId 
    from Contacts 
    group by ClientId 
    having sum(case when Guardian = 'Y' then 1 else 0 end) = 0 
)     
+0

でした!ありがとうございました! – jfe042

2

を使用しますが、contactid代わりのclientidを使用してサブクエリを接続したので、私はあなたがそれを経験していると考えている理由があります。私はまた、出力には明確な含めました:

select distinct c.ClientId 
from Contacts c 
where not exists (select 1 
        from Contacts c2 
        where c2.ClientId = c.ClientId 
        and c2.Guardian = 'Y') 
0
select * 
from contacts 
where ClientId not in 
(
    select ClientId 
    from contacts 
    where Guardian = 'Y' 
) 
関連する問題