Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Complex Query Help

Author  Topic 

mikeallenbrown
Yak Posting Veteran

72 Posts

Posted - 2014-05-30 : 10:56:36
The below query will return something like this

Combined.....InsuranceNumber....CompanyName
John Smith...5555555................Medicare
Jade White...7878787................Medical

If insurance doesn't equal 'Primary' or is NULL then the entire record doesn't show. What I want is for the records from Patient to appear even if no primary insurance was entered or if the insurance entered equals 'Primary'.

Combined.....InsuranceNumber....CompanyName
John Smith...5555555................Medicare
Mike Brown...5656565................
Jade White...7878787................Medical


SELECT Patient.ClientID, Patient.ID, Patient.MRNum, Patient.Compined, PatientStatus.Status, PatientStatus.Date, PatientStatus.DischargedDate, Patient.PrimDiag, PatientInsurance.InsuranceNumber, contact0.CompanyName, PatientLocation.Location4, PatientLocation.NPI AS NPI1 
FROM (Patient Patient
INNER JOIN PatientStatus PatientStatus
ON Patient.MRNum = PatientStatus.MRNum2 AND Patient.ClientID = PatientStatus.Clientid2
INNER JOIN (PatientInsurance PatientInsurance
INNER JOIN contact contact0
ON PatientInsurance.InsuranceID = contact0.id )
ON Patient.ID = PatientInsurance.PatientID
INNER JOIN PatientLocation PatientLocation
ON Patient.ID = PatientLocation.Patientid4 )
WHERE (PatientStatus.Status NOT IN ('Pending', 'Non-Admit') ) AND Patient.Record_delete <> 1 AND PatientInsurance.PrimaryOrSecondary = 'Primary'
ORDER BY Patient.Compined


Mike Brown

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2014-05-30 : 11:05:30
I really hate application generated sql code. Try this:

SELECT p.ClientID
, p.ID
, p.MRNum
, p.Compined
, ps.[Status]
, ps.[Date]
, ps.DischargedDate
, p.PrimDiag
, pIns.InsuranceNumber
, c.CompanyName
, pl.Location4
, pl.NPI AS NPI1
FROM Patient p
INNER JOIN PatientStatus ps
ON ps.MRNum2 = p.MRNum
AND ps.Clientid2 = p.ClientID
INNER JOIN PatientLocation pl
ON pl.Patientid4 = p.ID

left outer join PatientInsurance pIns
on pIns.PatientID = p.ID
and pIns.PrimaryOrSecondary = 'Primary'
left outer join contact c
on c.id = pIns.InsuranceID

WHERE ps.Status NOT IN ('Pending', 'Non-Admit')
AND p.Record_delete <> 1
ORDER BY p.Compined


EDIT:
added shorter table aliases
and changed the correlation column orders so that the JOINed table is referenced first - that doesn't matter but it is easier for me to read a statement that way.

Be One with the Optimizer
TG
Go to Top of Page

mikeallenbrown
Yak Posting Veteran

72 Posts

Posted - 2014-05-30 : 11:25:52
Thanks ....I'll give it a go

Mike Brown
Go to Top of Page
   

- Advertisement -