A clear explanation of computing total quantity sold per product using GROUP BY and SUM aggregation.
Problem Restatement
Using the Sales(sale_id, product_id, year, quantity, price) table, report the total quantity sold for each product.
Input and Output
| Table | Schema |
|---|---|
Sales | sale_id INT, product_id INT, year INT, quantity INT, price INT |
Return a table with product_id and total_quantity.
Edge Cases
- Match the aggregate to the question: use raw
COUNTorSUMfor rows/amounts, andCOUNT(DISTINCT ...)only for unique entities. - Tie cases should return every qualifying row unless the statement asks for a single row.
- For outer joins, keep filters on the joined table in the
ONclause when unmatched rows must remain visible.
Common Pitfalls
- Do not put aggregate filters in
WHERE; useHAVINGafterGROUP BY. - When the answer needs all tied winners, avoid
LIMIT 1unless the statement explicitly asks for one row.
Implementation
SELECT product_id, SUM(quantity) AS total_quantity
FROM Sales
GROUP BY product_id;Code Explanation
GROUP BY product_id groups all rows for the same product.
SUM(quantity) aggregates the total quantity sold for each group.