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

Time:03-23

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

CodePudding user response:

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

CodePudding user response:

Here you can use an inner join to join your Region table. This will only take into consideration the orders with a return since you are not using a OUTER JOIN. You then do your SUM the same as before. This will allow you to have the Total Returns. For the total of sales, my solution would be to do a sub query to select all of the sales, with or without a return.

SELECT REG.RegionID, SUM(O.SALES) AS Total_Sales, SUM(
    SELECT O.SALES 
    FROM ORDER O
    WHERE O.RegionID = REG.RegionID) AS Total_Returns
FROM ORDERS O
INNER JOIN REGION REG
    ON O.RegionID = REG.RegionID
INNER JOIN RETURNS RET
    ON O.OrderID = RET.OrderID
GROUP BY REG.RegionID
  • Related