⌨ Programming Medium SQL Aggregates

Top 10 Products by Total Revenue

Question

Find the top 10 products by total revenue (quantity Γ— unit_price from order_items). Return product name, units sold, and total revenue.

πŸ’‘ Join products and order_items.
SQL Editor
Solution
SELECT
  p.product_name,
  SUM(oi.quantity)                      AS units_sold,
  SUM(oi.quantity * oi.unit_price)      AS total_revenue
FROM products p
JOIN order_items oi ON p.product_id = oi.product_id
GROUP BY p.product_id, p.product_name
ORDER BY total_revenue DESC
LIMIT 10;
Explanation: JOIN products to order_items, GROUP BY product, compute revenue as SUM(quantity Γ— unit_price), then ORDER BY revenue and LIMIT 10.