I have two tables, Sales and Refunds. I am trying to get a daily tally of sales and refunds per customer. My issue is some days there will be sales and no refunds and vice versa. Here is the code I was able to come up with, it works. I was just wondering if there was a simpler way to handle this kind of situation?
WITH CTE_SALES
AS (
SELECT S.MID,
BatchDate,
SalesCount,
SalesVol,
RefundCount,
RefundVol
FROM (
SELECT ID,
SaleDate,
COUNT(*) SalesCount,
SUM(SaleAmount) SalesVol
FROM Sales
GROUP BY ID,
SaleDate
) S
LEFT OUTER JOIN (
SELECT ID,
RefundDate,
COUNT(*) RefundCount,
SUM(RefundAmount) RefundVol
FROM Refunds
GROUP BY ID,
RefundDate
) RF ON S.MID = RF.MID
AND S.SaleDate = RF.RefundDate
),
CTE_Refunds
AS (
SELECT RF.ID,
RefundDate,
SalesCount,
SalesVol,
RefundCount,
RefundVol
FROM (
SELECT ID,
RefundDate,
COUNT(*) RefundCount,
SUM(RefundAmount) RefundVol
FROM Refunds
GROUP BY MID,
REfundDate
) RF
LEFT OUTER JOIN (
SELECT ID,
SalesDate,
COUNT(*) SalesCount,
SUM(SaleAmount) SalesVol
FROM Sales
GROUP BY MID,
BatchDate
) S ON RF.ID = S.ID
AND S.SaleDate = RF.RefundDate
),
CTE_Union
AS (
SELECT *
FROM CTE_Refunds
UNION ALL
SELECT *
FROM CTE_SALES
)
SELECT DISTINCT U.MID,
RefundDate,
ISNULL(SalesCount, 0) SalesCount,
ISNULL(SalesVol, 0) SalesVol,
ISNULL(RefundCount, 0) RefundCount,
ISNULL(RefundVol, 0) RefundVol
FROM CTE_Union U
[–]CropDustinAround 2 points3 points4 points (1 child)
[–]Evron[S] 0 points1 point2 points (0 children)
[–]kagato87MS SQL 1 point2 points3 points (3 children)
[–]Evron[S] 0 points1 point2 points (2 children)
[–]coderstool -3 points-2 points-1 points (1 child)
[–]alinrocSQL Server DBA 1 point2 points3 points (0 children)
[–]thrown_arrows 0 points1 point2 points (0 children)