Interview Puzzles · Problem 106 of 118

Year-over-Year Revenue by Category

HardInterview PuzzlesShop data

Revenue is the sum of quantity * unit_price over lines of non-cancelled orders. For each category that has revenue in 2025, return the category name as category, revenue_2025, revenue_2026 (both rounded to 2 decimals, 0 if none) and growth_percent: (revenue_2026 - revenue_2025) / revenue_2025 * 100, rounded to 1 decimal. Sort by growth_percent from high to low, then category.

Hint 1

One pass over the joined rows with SUM(CASE WHEN order_date BETWEEN ... THEN ... END) for each year.

Reference solution

WITH yearly AS (
  SELECT c.name AS category,
         ROUND(SUM(CASE WHEN o.order_date BETWEEN '2025-01-01' AND '2025-12-31' THEN oi.quantity * oi.unit_price ELSE 0 END), 2) AS revenue_2025,
         ROUND(SUM(CASE WHEN o.order_date BETWEEN '2026-01-01' AND '2026-12-31' THEN oi.quantity * oi.unit_price ELSE 0 END), 2) AS revenue_2026
  FROM orders AS o
  JOIN order_items AS oi ON oi.order_id = o.order_id
  JOIN products AS p ON p.product_id = oi.product_id
  JOIN categories AS c ON c.category_id = p.category_id
  WHERE o.status <> 'cancelled'
  GROUP BY c.category_id, c.name
)
SELECT category,
       revenue_2025,
       revenue_2026,
       ROUND(100.0 * (revenue_2026 - revenue_2025) / revenue_2025, 1) AS growth_percent
FROM yearly
WHERE revenue_2025 > 0
ORDER BY growth_percent DESC, category;

Year-over-year comparison puts two periods side by side as columns, which is conditional aggregation again: each SUM(CASE ...) is one period. Growth is always measured against the base period (the earlier year); dividing by the later year understates growth. Guard against division by zero with WHERE revenue_2025 > 0 (a category that did not sell last year has no meaningful growth rate). Note that the 2026 data stops at 30 September: in a real report you would compare the same months of both years.