解決SQL左外連接中日期篩選問題
你的SQL查詢中,左外連線沒有回傳預期的結果。具體來說,當你在WHERE子句中包含日期參數時,在右側表中沒有符合資料的銷售代表不會顯示。
為了解決這個問題,你需要將prescriptions
表的日期約束移到連接的ON
條件中,而不是保留在WHERE
子句中:
<code class="language-sql">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 AND prescriptions.filldate >= '09-01-12' AND prescriptions.filldate <= '09-17-12' ORDER BY prescriptions.filldate</code>
透過將約束條件移到ON
條件中,你可以確保左外連接正確地傳回所有銷售代表的結果,無論prescriptions
表中是否存在符合記錄。
以上是當我按日期篩選時,為什麼我的左外連線不回傳所有銷售代表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!