Which Products Make Half the Revenue
Revenue of a product is the sum of quantity * unit_price over all its order lines, rounded to 2 decimals. Rank products by revenue (highest first; ties by product_id) and add up the revenue as you go down the list.
Return product_id, revenue and cumulative_percent (the running total as a percentage of the total revenue of all products, rounded to 1 decimal) for the products needed to reach at least 50%: that is, every product whose cumulative total before it is still below 50% of the total. Sort by revenue from high to low, then product_id.
Hint 1
Two window sums over the same rows: one running (ORDER BY revenue DESC, product_id), and one over everything (OVER ()).
Hint 2
Keep a row when running_total - revenue (the total before this row) is below half of the grand total.
Reference solution
WITH rev AS (
SELECT product_id, ROUND(SUM(quantity * unit_price), 2) AS revenue
FROM order_items
GROUP BY product_id
), cum AS (
SELECT product_id, revenue,
SUM(revenue) OVER (ORDER BY revenue DESC, product_id) AS running,
SUM(revenue) OVER () AS total
FROM rev
)
SELECT product_id,
revenue,
ROUND(100.0 * running / total, 1) AS cumulative_percent
FROM cum
WHERE running - revenue < 0.5 * total
ORDER BY revenue DESC, product_id;
This is a Pareto (80/20) analysis: how concentrated is revenue? The subtle part is the boundary. The product that crosses the 50% line belongs in the answer (without it the set does not reach 50%), and its running total is already above 50%. Testing the total before the row (running - revenue) includes exactly that product. Boundary conditions like this are where analysts lose points; check yours with a tiny example.