I have a weird one that is hard to explain.
So I am looking for any Providers that are not listed as a Primary. So I did a select PROVID from PROVSPECIALTY (#primary) table which gives me about 73000 rows of PROVIDs. Then I did a select PROVID from PROVSPECIALTY where SPECTYPE = 'SECONDARY' (#sec) which gives 3600 rows. Then I ran select distinct * from #sec where provid not in (select distinct * from #primary) which gives me what I want which is 192 rows.
What my question is is how can I join the 192 records to my base table to get all the fields needed for those provids?
I have tried every kind of join, where exists, etc.
This is the base table that gets all the fields:
select distinct
mp.Affiliationid,
a1.provid as "PCP Provid",
p1.Fullname,
p1.Provtype,
a1.Affiltype,
a1.affiliateid as "PCP Affiliate",
p2.fullname as Fullname2,
p2.provtype as Provtype2,
a1.payflag as Payflag1,
a1.PCP,
mp.Enrollid,
mp.Pcptype,
Spectype,
mp.Specialtycode,
z.description as 'Specialty Description',
mp.Paytoaffilid,
a2.provid as "Payto Provid",
p3.fullname as Fullname3,
p3.provtype as Provtype3,
a2.affiltype as Affiltype2,
a2.affiliateid as "Payto Affiliate",
a2.payflag,
p4.fullname as Fullname4,
p4.provtype as Provtype4,
a2.payflag as Payflag2,
a2.pcp as PCP2,
cast(mp.effdate as date) as PCPEffdate,
cast(mp.termdate as date) as PCPTermdate,
mp.Svczip,
mp.Createid,
mp.Createdate,
mp.Lastupdate,
mp.Updateid,
ci.ContractID,
cast(ek.effdate as date) as EnrollEff,
cast(ek.termdate as date) as EnrollTerm,
Flag = ''
into #BASE
from qnxt.dbo.memberpcp mp
join qnxt.dbo.affiliation a1 (nolock) on mp.affiliationid = a1.affiliationid
join qnxt.dbo.affiliation a2 (nolock) on mp.paytoaffilid = a2.affiliationid
join qnxt.dbo.provider p1 (nolock) on a1.provid = p1.provid
join qnxt.dbo.provider p2 (nolock) on a1.affiliateid = p2.provid
join qnxt.dbo.provider p3 (nolock) on a2.provid = p3.provid
join qnxt.dbo.provider p4 (nolock) on a2.affiliateid = p4.provid
join qnxt.dbo.provspecialty y (nolock) on p1.provid = y.provid
join qnxt.dbo.specialty z (nolock) on mp.specialtycode = z.specialtycode
left join qnxt.dbo.affiliation_audit aa (nolock) on a1.affiliationid = aa.affiliationid
left join qnxt.dbo.provider pr (nolock) on aa.provid = pr.provid
left join qnxt.dbo.entity e (nolock) on p1.entityid =e.entid
left join qnxt.dbo.contractinfo ci (nolock) on mp.paytoaffilid = ci.affiliationid
join QNXT.[dbo].[enrollkeys] ek (nolock) on mp.enrollid = ek.enrollid
join QNXT.dbo.memberpcp x (nolock) on x.enrollid = ek.enrollid
where mp.termdate > '2017-01-01'
I wasn't sure what information to include in terms of data but if someone could give me a lead on how to solve this I will be happy to include test data. Thank you for any help!