MS Access 多重加入标准

MS Access multiple joins with criteria

我正在生成一个库存查询,下面的代码(大部分)有效,但它包括已作废的发票,导致负库存。

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;

这样试试:

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'

的产品