以下查询在2个单独的表上的子查询中完成了聚合计算,并将这些值传递给主查询。
(请注意以上消息,以下发布的代码已根据Andre的评论进行了更新。原始代码因错误而未运行。)
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
;
答案 0 :(得分:0)
第二次尝试,根据您的原始查询 - 您可以解释所有错误:
totSales.Year-Month
:您必须将它放在方括号中,包括SELECT和GROUP BY子句:totSales.[Year-Month]
。
否则,它被解释为[totSales.Year] minus [Month]
。
SELECT SUM(totReturns.[Return Sales])
但在totReturns
中您有AS [Returns Sales]
(请注意退货中的额外“s”。
TotCommissions, TotLostCommissions
:这两个字段未在FROM子句中的任何位置定义。