Joins · Problem 44 of 118

Revenue per Category

MediumJoinsShop data

Revenue of a line is quantity * unit_price. Return the category name as category and its revenue (the sum over all lines of products in that category, rounded to 2 decimals). Sort by revenue from high to low.

Hint 1

The path is order_items to products to categories.

Hint 2

Group by the category, and put the ROUND around the SUM.

Reference solution

SELECT c.name AS category,
       ROUND(SUM(oi.quantity * oi.unit_price), 2) AS revenue
FROM order_items AS oi
JOIN products AS p ON p.product_id = oi.product_id
JOIN categories AS c ON c.category_id = p.category_id
GROUP BY c.category_id, c.name
ORDER BY revenue DESC;

order_items.unit_price is the price at the time of the sale; products.price is today's price. They can differ, and revenue must use the price actually charged. This is a classic data-model detail: the line stores its own price so history stays correct when prices change. Group by the category's id as well as its name, so two categories that happened to share a name would never be merged.