我有一个查询,使用两个外部连接的LEFT OUTER JOIN从三个表中提取数据。我需要查询返回最左边的(Salesrep表)信息,即使在两个右边的表(分别是处方药和处方)中没有对应的数据也是如此。当我在WHERE子句中没有日期参数的情况下运行此查询时,我得到了预期的返回,但是当我包含日期参数时,在没有任何销售代表匹配数据的情况下,我什么也没有得到返回。我至少需要查看查询中请求的salesrep表列。

这是查询...非常感谢您的帮助。

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

最佳答案

您应该将对prescriptions.filldate的约束移到联接的ON条件中,并将其从where子句中删除:

LEFT OUTER JOIN prescriptions ON prescriber.dea_no = prescriptions.dea_no
                             AND prescriptions.filldate >= '09-01-12'
                             AND prescriptions.filldate <= '09-17-12'

否则,没有prescriptions的条目将以null中的prescriptions.filldate结尾,并且WHERE子句将其丢弃。

10-04 11:14