SELECT SUM(numberofsales) as numberofsales,SUM(salevalue)
FROM (
--handle sales with refunds
SELECT count(sales) as numberofsales, sum(sales.value-refunds.value) as salevalue
FROM Transactions sales
LEFT JOIN transactions refunds ON sales.transid=refunds.refundid
WHERE refunds.refundid IS NOT NULL
AND sales.value-refund.value>0
AND sales.date>@begindate
AND sales.date<@enddate
AND sales.refund_flag='s'
UNION
--handle sales without refunds
SELECT count(sales) as numberofsales, sum(sales.value) as salevalue
FROM Transactions sales
LEFT JOIN transactions refunds ON sales.transid=refunds.refundid
WHERE refunds.refundid IS NULL
AND sales.date>@begindate
AND sales.date<@enddate
AND sales.refund_flag='s')
這是第一次與解決方案的主要特點。 它使用SQL Server語法,我不確定sql server和mysql之間的區別。
根據michael667的回答以上,你可以看到自我加入以獲得每筆銷售的退款。 我不認爲組是必需的。
此解決方案不會確保每次銷售只有一次退款,並且實際上如果有多個退款,這會影響此解決方案的正確性。
輝煌,指出我在正確的方向! –