簡體   English   中英

返回依賴於另一列中的值的值

[英]Return values that relies on a value from another column

我以為這很容易,但是由於某種原因,我無法解決這個問題。 也許我很累。 無論如何,我想返回一個狀態碼為1和4的策略值。我有一個簡單的查詢:

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

結果: 在此處輸入圖片說明

看到突出顯示的策略ID 10241嗎? 我只希望它們返回,因為它的edeliverystatuscd為1和4。因此,我希望狀態碼為1和4的policyid僅返回,而忽略其余部分。 我認為這應該很簡單。 我不知道為什么,但今天我不知道。 任何幫助表示贊賞!

只需添加group byhaving

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

如果該表在policyid 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

使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM