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:
select policiesid, eDeliveryStatusCd
from UserPolicyHistory
where PoliciesID is not null
and eDeliveryStatusCd in (1,4)
order by policiesid
See the highlighted policiesid of 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. 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
:
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. 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()
:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.