[英]Return values that relies on a value from another column
I thought this would be pretty easy but for some reason, I can't wrap my head around it. 我以为这很容易,但是由于某种原因,我无法解决这个问题。 Maybe I am tired.
也许我很累。 Anyway, I want to return a policy value that has a status code of 1 and 4. I have a simple query:
无论如何,我想返回一个状态码为1和4的策略值。我有一个简单的查询:
select policiesid, eDeliveryStatusCd
from UserPolicyHistory
where PoliciesID is not null
and eDeliveryStatusCd in (1,4)
order by policiesid
See the highlighted policiesid of 10241? 看到突出显示的策略ID 10241吗? I want only those to return because it has an edeliverystatuscd of 1 and 4. So I want a policiesid that has a status code of 1 and 4 to return only, ignoring the rest.
我只希望它们返回,因为它的edeliverystatuscd为1和4。因此,我希望状态码为1和4的policyid仅返回,而忽略其余部分。 I thought it should be pretty simple.
我认为这应该很简单。 I don't know why but I can't figure it out today.
我不知道为什么,但今天我不知道。 Any help is appreciated!
任何帮助表示赞赏!
Just add group by
and having
: 只需添加
group by
并having
:
select policiesid
from UserPolicyHistory
where PoliciesID is not null and eDeliveryStatusCd in (1, 4)
group by policiesid
having count(distinct eDeliveryStatusCd) = 2;
The other answer works if the table is unique on policiesid, eDeliveryStatusCd. 如果该表在policyid eDeliveryStatusCd上唯一,则另一个答案有效。 If not try:
如果不尝试:
select policiesid, count(*)
from (select distinct policiesid, eDeliveryStatusCd
from UserPolicyHistory uph1
where PoliciesID is not null
and eDeliveryStatusCd in (1,4))
having count(*) > 2
using exists()
: 使用
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.