MS使用条件访问多个联接

时间:2017-08-04 06:52:57

标签: sql ms-access-2016

我生成了一个库存查询,下面的代码(大部分)都有效,但它包括已经无效的发票,导致库存负数。

Void Yes/No field = tblInvoices.Void

tblInvoiceDetails.InvoiceNum = tblInvoices.ID

我无法弄清楚如何确保这不包括无效的发票。提前感谢您的帮助!

SELECT tblInventory.ID, Nz(sumTotalPaid,0)-Nz(sumCreditAmount,0) AS Quantity
FROM (tblInventory 
LEFT JOIN (
    SELECT ProductID, Sum(Quantity) AS sumTotalPaid
    FROM tblOrderDetails
    GROUP BY tblOrderDetails.ProductID
)  AS sum1 
   ON tblInventory.ID = sum1.ProductID) 
LEFT JOIN (
    SELECT ProductID, Sum(Quantity) AS sumCreditAmount
    FROM tblInvoiceDetails
    GROUP BY tblInvoiceDetails.ProductID
)  AS sum2 
    ON tblInventory.ID = sum2.ProductID;

1 个答案:

答案 0 :(得分:0)

以这种方式尝试:

SELECT tblInventory.ID, Nz(sumTotalPaid,0)-Nz(sumCreditAmount,0) AS Quantity
FROM (tblInventory  
JOIN (
    SELECT ProductID, Sum(Quantity) AS sumTotalPaid
    FROM tblOrderDetails
    GROUP BY tblOrderDetails.ProductID
)  AS sum1 
   ON tblInventory.ID = sum1.ProductID) 
JOIN (
    SELECT ProductID, Sum(Quantity) AS sumCreditAmount
    FROM tblInvoiceDetails
    WHERE tblInvoiceDetails.InvoiceNum IN 
        (SELECT tblInvoices.ID
        FROM tblInvoices
        WHERE tblInvoices.Void='Yes')
    GROUP BY tblInvoiceDetails.ProductID
)  AS sum2 
    ON tblInventory.ID = sum2.ProductID

1.-首先,您只使用JOIN代替LEFT JOIN,因此您只需获取两个表中包含值的行。

2.-您只获得具有tblInvoices.Void='Yes'

的产品