1
以下查詢具有在2個獨立表上的子查詢中完成的聚合計算,並將這些值傳遞給主查詢。訪問查詢不識別子查詢的值
(注意:上述信息,下面貼出的代碼是基於從安德烈的意見更新。原代碼沒有因運行錯誤。)
SELECT
totSales.[Month] & " /" AS [Month],
totSales.[Year] AS [Year],
SALES_REP.rep_name AS [Sales Person],
Sum(totSales.[Total Sales]) AS [Total Sales],
Sum(totSales.[Gross Commission]) AS [Gross Commission],
Sum(Nz(totReturns.[Sales Returns],0)) AS [Sales Returns],
Sum(Nz(totReturns.[Lost Commission],0)) AS [Lost Commission],
Round([Gross Commission]-[Lost Commission]) AS [Net Commission]
FROM SALES_REP
INNER JOIN
(
(SELECT
Format(SALES_RECEIPT.sale_date,'yyyy') AS [Year],
Format(SALES_RECEIPT.sale_date,'mm') AS [Month],
Sales_receipt.inventory_id, SALES_RECEIPT.rep_id,
(SALES_RECEIPT.selling_price * SALES_RECEIPT.quantity) AS [Total Sales],
((Nz(SALES_RECEIPT.selling_price, 0) * Nz(SALES_RECEIPT.quantity, 0)) * (Nz(SALES_RECEIPT.commission_percent, 100) * 0.001)) AS [Gross Commission]
FROM SALES_RECEIPT
WHERE SALES_RECEIPT.sale_date Between #1/1/2000# And #12/31/2050#) AS totSales
LEFT JOIN
(SELECT
RETURNS.rep_id, returns.inventory_id, (Nz(RETURNS.selling_price)) * (Nz(RETURNS.quantity)) AS [Sales Returns],
((Nz(RETURNS.selling_price, 0) * Nz(RETURNS.quantity, 0)) * (Nz(RETURNS.commission_percent, 100) * 0.001)) AS [Lost Commission]
FROM RETURNS
WHERE RETURNS.return_date Between #1/1/2000# And #12/31/2050#) AS totReturns
ON totSales.inventory_id = totReturns.inventory_id)
ON SALES_REP.rep_id = totSales.REP_ID
GROUP BY
totSales.[Year]
, totSales.[Month]
, SALES_REP.rep_name
;
感謝您的更新,我有我最新的代碼上面貼有修改後的消息。查詢運行時沒有錯誤,但「總銷售額」值是它應該的值的兩倍。 「銷售退貨」值不正確,其中許多「銷售退貨」值是「總銷售額」的3到4倍,這是正常的。 –
如果我將Nz函數添加到下面的代碼行中,我會得到錯誤:「標準表達式中的數據類型不匹配」。 Nz(RETURNS.selling_price * RETURNS.quantity)AS [Return Sales],由於有幾個月沒有回報,我想使用Nz函數,所以我得到零而不是空值。 –
@CodeMechanik:我無法幫助錯誤的數字 - 也許一個連接創建重複的記錄,然後總結。你應該在一個新問題中用[SQL小提琴](http://sqlfiddle.com/)和樣本數據來提問。 – Andre