SQL 50, decoded
0 of 50 solved/50

1070. Product Sales Analysis III

SQL 50 · Sorting and Grouping (day 4). Decode it with the hints, solve it on LeetCode, then compare with the reference solution in MySQLPostgreSQL.

MediumSolve it on LeetCode ↗

Your work

Hints

Open one at a time. Try to finish with as few as you can.

1. What does one output row represent?
One sale in its product’s first year.
2. Approach
WHERE (product_id, year) IN (SELECT product_id, MIN(year) … GROUP BY product_id).
3. The trap
A product can have several sales in its first year; keep them all.

Reference solution

Tested on MySQL 8.0 and PostgreSQL 16. Switch dialect at the top of the page.

Show the MySQLPostgreSQL solution
SELECT product_id, year AS first_year, quantity, price
FROM Sales
WHERE (product_id, year) IN (
  SELECT product_id, MIN(year)
  FROM Sales
  GROUP BY product_id
);

Patterns used

Toolbox · Phrase finder