Skip to content

LeetCode 1069: Product Sales Analysis II

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

TableSchema
Salessale_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 COUNT or SUM for rows/amounts, and COUNT(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 ON clause when unmatched rows must remain visible.

Common Pitfalls

  • Do not put aggregate filters in WHERE; use HAVING after GROUP BY.
  • When the answer needs all tied winners, avoid LIMIT 1 unless 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.