Interview Puzzles · Problem 103 of 118

Best Seller per Category

HardInterview PuzzlesShop data

For every category that has products, return category_id, product_id and units (the sum of quantity over all its order lines) for the product (or products, if tied) with the most units sold in its category. Sort by category_id, then product_id.

Hint 1

First units per product with its category, then RANK() inside each category.

Reference solution

WITH units AS (
  SELECT p.category_id, p.product_id, SUM(oi.quantity) AS units
  FROM order_items AS oi
  JOIN products AS p ON p.product_id = oi.product_id
  GROUP BY p.category_id, p.product_id
), ranked AS (
  SELECT category_id, product_id, units,
         RANK() OVER (PARTITION BY category_id ORDER BY units DESC) AS r
  FROM units
)
SELECT category_id, product_id, units
FROM ranked
WHERE r = 1
ORDER BY category_id, product_id;

Three layers: aggregate per product, rank per category, filter on rank. RANK() keeps all tied products at rank 1, which is the fair answer to "best seller"; ROW_NUMBER() would pick one of them arbitrarily. If two products tie, a report that shows only one is quietly hiding information.