My JOIN doubled the totals: the SQL Server grain mistake
You joined Orders to OrderLines to get product names and the revenue doubled. Nothing is wrong with SUM. The grain changed and nobody told SUM.
What happened
One order of £90 with three lines becomes three rows after the join. SUM(o.total_amount) adds £90 three times.
-- Inflated
SELECT SUM(o.total_amount) AS revenue
FROM Orders o
JOIN OrderLines ol ON ol.order_id = o.order_id;
Aggregate the lines first
SELECT o.order_id, o.total_amount, x.lines, x.units
FROM Orders o
JOIN (
SELECT order_id, COUNT(*) AS lines, SUM(quantity) AS units
FROM OrderLines
GROUP BY order_id
) x ON x.order_id = o.order_id;
Now one row per order. Totals stay honest. You can still SUM(o.total_amount) outside.
If you want revenue from lines, sum quantity * unit_price on OrderLines. If you want the order total, stay on Orders and do not join lines in the same grain.
Try it on Harbour & Co
Kwame Asante (Data Analyst) needs this now: “My top-10 spenders query gives numbers way higher than finance’s. Can you see why?” Write the query, run it, send the results. On the paid plan.
Take the ticket →Learn it on a real ticket
Monday is free on WorkSQL. A colleague’s ticket lands, you write the T-SQL, we mark it. No videos. Five minutes.
Clock in free See Monday’s tickets