How to sum values based on a second table, and group them by a third?

Advertisements

I have 3 tables: Orders, Returns, Region

OrderID Sales RegionID
1 100 1
2 200 2
3 200 2
ReturnID OrderID
1 1
2 3
RegionID Region
1 N
2 E

I’m trying to sum the total sales and returns and group them by region. I’m trying to join the third table of returns, to only display the sum of the sales where there is a OrderID in the return table matching an OrderID from the Order table and grouped by RegionID, but I’m having trouble figuring it out.

I have it working for total sales in a region using:

SELECT r.Region, SUM(o.sales)
FROM Orders o
INNER JOIN Region r ON o.RegionID = r.RegionID
GROUP BY o.RegionID

Edit:

Final result should look like:

RegionID Total Sales Total Returns
1 100 100
2 400 200
3 0 0

>Solution :

Try this:

SELECT
    r.RegionID
    , SUM(o.sales) [Total Sales]
    , SUM(CASE WHEN rt.orderId IS NOT NULL THEN o.sales ELSE 0 END) [Total Returns]
FROM Orders o
INNER JOIN Region r ON o.RegionID = r.RegionID
LEFT JOIN returns rt ON rt.orderId=o.orderId
GROUP BY o.RegionIDvalues

Leave a ReplyCancel reply