2017-02-21 50 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

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

@Lisbon樂於助人! – 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。 。 。不,事實上,它並沒有做出這樣的假設。你知道「數(不同)」是什麼嗎? –

+0

對不起,錯過了那部分的sql。 – MikeS

1

對方回答,如果工作表是policiesid,eDeliveryStatusCd獨特。如果不嘗試:用exists()

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