Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading