繁体   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