2017-02-21 10 views
0

これはかなり簡単だと思っていましたが、なんらかの理由で私はそれを取り巻くことができません。たぶん私は疲れているでしょう。とにかく、私は単純なクエリを持っている1〜4のステータスコードを持つポリシーの値を返すようにしたい:別の列からの値に依存する戻り値

select policiesid, eDeliveryStatusCd 
from UserPolicyHistory 
where PoliciesID is not null 
and eDeliveryStatusCd in (1,4) 
order by policiesid 

結果: enter image description here

10241の強調表示さpoliciesidを参照してください?私は1と4のedeliverystatuscdを持っているので、私は戻ってほしい。だから、残りのものを無視して、1と4の状態コードだけを返すpoliciesidがほしい。私はそれがかなりシンプルであるべきだと思った。なぜか分からないけど、今日は分からない。どんな助けもありがとう!

答えて

1

exists()を使用して:

select policiesid, eDeliveryStatusCd 
from UserPolicyHistory as t 
where PoliciesID is not null 
    and eDeliveryStatusCd in (1,4) 
    and exists (
    select 1 
    from UserPolicyHistory as i 
    where i.policiesid = t.policiesid 
     and i.eDeliveryStatusCd in (1,4) 
     and i.eDeliveryStatusCd <> t.eDeliveryStatusCd 
) 
order by policiesid 
+0

私はこれが好きです!ありがとう! – Lisbon

+0

@リスボン幸せに助けて! – SqlZim

2

だけgroup byhavingを追加します。

select policiesid 
from UserPolicyHistory 
where PoliciesID is not null and eDeliveryStatusCd in (1, 4) 
group by policiesid 
having count(distinct eDeliveryStatusCd) = 2; 
+0

これはpoliciesidとeDeliveryStatusCdに独自性があることが前提になります。 – MikeS

+0

@MikeS。 。 。いいえ、実際には、その仮定をしません。 'count(distinct) 'が何をするのか知っていますか? –

+0

申し訳ありませんが、SQLのその部分を逃した。 – MikeS

1

表はpoliciesid、eDeliveryStatusCd上で一意であれば、他の答えは動作します。しようとしない場合:

select policiesid, count(*) 
from (select distinct policiesid, eDeliveryStatusCd 
    from UserPolicyHistory uph1 
    where PoliciesID is not null 
    and eDeliveryStatusCd in (1,4)) 
having count(*) > 2 
関連する問題