我有一个SALES_RECEIPT
表和一个(sales)RETURNS
表,它们都有REP_ID
作为SALES_REP
表中的外键。我想总结每个销售代表的总销售额和总回报,并计算销售佣金和退货佣金。
查询运行时没有错误,但列中的值不正确。这些值远大于实际值。我尝试了INNER JOIN和LEFT JOIN来链接RETURNS表,但这并没有解决问题。
SELECT Format(SALES_RECEIPT.SALE_DATE,'yyyy-mm') AS [Year-Month],
SALES_REP.rep_Name,
Sum(SALES_RECEIPT.SELLING_PRICE*SALES_RECEIPT.quantity) AS [Total Sales],
Sum((Nz(SALES_RECEIPT.SELLING_PRICE,0)*Nz(SALES_RECEIPT.quantity,0))*(Nz(SALES_RECEIPT.commission_percent,100)*0.001)) AS [Gross Commission],
Sum(Nz(returns.selling_price * returns.quantity)) AS [Returns Sales],
Sum(Nz(returns.selling_price*returns.quantity)) AS [Returns Sales], Sum((Nz(RETURNS.SELLING_PRICE,0)*Nz(RETURNS.quantity,0))*(Nz(RETURNS.commission_percent,100)*0.001)) AS [Lost Commission],
Sum((Nz(SALES_RECEIPT.SELLING_PRICE,0)*Nz(SALES_RECEIPT.quantity,0))*(Nz(SALES_RECEIPT.commission_percent,100)*0.001))-Sum((Nz(RETURNS.SELLING_PRICE,0)*Nz(RETURNS.quantity,0))*(Nz(RETURNS.commission_percent,100)*0.001)) AS [Net Commission]
FROM
(SALES_RECEIPT INNER JOIN SALES_REP ON SALES_RECEIPT.REP_ID = SALES_REP.REP_ID)
LEFT JOIN RETURNS ON SALES_RECEIPT.REP_ID = RETURNS.REP_ID
WHERE (((SALES_RECEIPT.SALE_DATE) Between #1/1/2000# And #12/31/2050#))
GROUP BY Format(SALES_RECEIPT.SALE_DATE,'yyyy-mm'), SALES_REP.rep_Name;
答案 0 :(得分:0)
为Access编辑(尝试修复语法)
假设RETURNS表具有SALES_RECEIPT表的密钥ID?
首先,根据日期范围拉出所有SalesReceipt记录 然后,根据相同的日期范围拉出所有RETURNS
WITH totSales as
(
SELECT
sr.SalesReceiptID
,sr.REP_ID
,Format(sr.SALE_DATE,'yyyy-mm') AS [Year-Month]
,(sr.SELLING_PRICE * sr.quantity) AS [Total Sales]
,((Nz(sr.SELLING_PRICE, 0) * Nz(sr.quantity, 0)) * (Nz(sr.commission_percent, 100) * 0.001)) AS [Gross Commission]
FROM
SALES_RECEIPT sr
WHERE
sr.SALE_DATE Between #1/1/2000# And #12/31/2050#
)
,totReturns as
(
SELECT
r.REP_ID
,(Nz(returns.selling_price * returns.quantity)) AS [Returns Sales]
,((Nz(RETURNS.SELLING_PRICE, 0) * Nz(RETURNS.quantity, 0)) * (Nz(RETURNS.commission_percent, 100) * 0.001)) AS [Lost Commission]
FROM
RETURNS r
WHERE
r.RETURN_DATE Between #1/1/2000# And #12/31/2050#
)
Select
ts.Year-Month
,sr.REP_Name
,SUM(ts.[Total Sales]) as 'TotSales'
,SUM(ts.[Gross Commission]) as 'TotCommissions'
,SUM(ISNULL(tr.[Return Sales],0) as 'TotReturnSales'
,SUM(ISNULL(tr.[Lost Commission],0) as 'TotLostCommissions'
From totSales ts
LEFT JOIN totReturns tr on tr.SalesReceiptID = ts.SalesReceiptID
INNER JOIN
SALES_REP sr ON ts.REP_ID = sr.REP_ID)
Group By ts.Year-Month, ts.REP_Name;
从上次评论中,我修改了第二个CTE,以获得SALES_RECEIPT CTE中使用的相同日期范围内的所有RETURNS。这应该为您提供在特定销售代表分组的同一日期范围内的销售额,佣金,退货和丢失佣金的适当总和。