The question:
I want to get the total refund amount in the last 365 days. However, This return the total refund amount (not last 365 days only). What should be the right way to do this?
SELECT sum(a.total_amount) AS TotalRefund365Days
from [dbo].[UserPurchase] a
inner join [dbo].[UserPurchaseRefunds] b
on a.user_purchase_id = b.user_purchase_id
where a.is_refunded = 1 AND b.DateCreated > (getdate() - 365)
Note: ([dbo].[UserPurchaseRefunds].Amount is total purchase quantity which is not required)
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
I think your issue is what David Browne pointed out in your other post regarding this, which is your relationship between the dbo.UserPurchase
and dbo.UserPurchaseRefunds
is one-to-many. This results in your current query are double counting the Total_Amount
.
What you want to do is use a CTE or subquery to de-dupe the redundant rows first, then aggregate the remaining rows, like so:
SELECT SUM(RefundedAmounts.total_amount) AS TotalRefund365Days
FROM
(
SELECT a.total_amount
FROM dbo.UserPurchase a
INNER JOIN dbo.UserPurchaseRefunds b
ON a.user_purchase_id = b.user_purchase_id
WHERE a.is_refunded = 1
AND b.DateCreated > (GETDATE() - 365)
GROUP BY a.user_purchase_id, a.total_amount
) AS RefundedAmounts
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0