解决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中文网其他相关文章!