Skip to content

LeetCode 1084: Sales Analysis III

A clear explanation of finding products sold only in the first quarter of 2019 using GROUP BY with date range conditions.

Problem Restatement

Using Sales(sale_id, product_id, buyer_id, sale_date, quantity, price) and Product(product_id, product_name, unit_price), report products that were sold only between 2019-01-01 and 2019-03-31 (Q1 2019).

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 s.product_id, p.product_name
FROM Sales s
JOIN Product p ON s.product_id = p.product_id
GROUP BY s.product_id, p.product_name
HAVING MIN(s.sale_date) >= '2019-01-01'
   AND MAX(s.sale_date) <= '2019-03-31';

Code Explanation

Group by product_id to get all sales for each product.

MIN(sale_date) >= '2019-01-01' ensures no sale before Q1 2019.

MAX(sale_date) <= '2019-03-31' ensures no sale after Q1 2019.

Together, these conditions confirm all sales for the product are within Q1 2019.