I have a query pulling data from three tables using LEFT OUTER JOIN for both joins. I need the query to return the left most (Salesrep table) info even if the there is no corresponding data in the two right tables (prescriber and prescriptions, respectively). When I run this query without the date parameters in the WHERE clause, I get the expected return, but as soon as I include the date parameters I get nothing returned where there is no matching data for a salesrep. I need to at least see the salesrep table columns requested in the query.
Here is the query… any help is VERY much appreciated.
SELECT salesrep.salesrepid as SalesRepID,
salesrep.fname as SalesrepFName,
salesrep.lname as SalesRepLName,
salesrep.fname+' '+salesrep.lname as SalesRepFullName,
prescriber.dea_no as PDeaNo,
prescriber.lname+', '+prescriber.fname as DocName,
CONVERT(VARCHAR(8), prescriptions.filldate, 1) as FillDate,
prescriptions.drugname as DrugName,
prescriptions.daysupply as Supply,
prescriptions.qtydisp as QtyDisp,
prescriptions.rx_no as Refill,
prescriptions.copay as Sample,
ROUND(prescriptions.AgreedToPay-(prescriptions.AgreedToPay*.07),2) as AgreedToPay,
prescriptions.carrierid as CarrierID
FROM salesrep
LEFT OUTER JOIN prescriber on salesrep.salesrepid = prescriber.salesrepid
LEFT OUTER JOIN prescriptions on prescriber.dea_no = prescriptions.dea_no
WHERE salesrep.salesrepid = 143 AND
prescriptions.filldate >= '09-01-12' AND
prescriptions.filldate <= '09-17-12'
ORDER BY prescriptions.filldate
You should move the constraints on
prescriptions.filldateinto theONcondition of the join, and remove it from thewhereclause:Otherwise, entries for which there are no
prescriptionsend up withnulls inprescriptions.filldate, and theWHEREclause throws them away.