SQL Practice: Supplier Margin Report
Close the operations chapter by ranking suppliers on shipped gross margin.
Revenue alone doesn't tell the whole supplier story. A supplier can sell a
lot of product but produce a thinner margin if costs are high. This report
compares shipped revenue, estimated cost, gross margin, and margin rate. The
cost estimate uses the product table's current cost for every
past sale, because Garden Shop doesn't record what an item cost when it
sold.
The query walks across four tables: suppliers to products, products to line items, and line items to orders so only shipped sales count.
Margin is a line-item calculation
Calculate margin before summing:
quantity * (unit_price - cost). Then divide total margin by total revenue for the margin percentage.
select supplier_name,
round(sum(quantity * sale_price), 2) as revenue,
round(sum(quantity * unit_cost), 2) as cost,
round(sum(quantity * (sale_price - unit_cost)), 2) as gross_margin,
round(100.0 * sum(quantity * (sale_price - unit_cost)) / sum(quantity * sale_price), 1) as margin_pct
from joined_sales
group by supplier_name
order by gross_margin desc
limit 5 Schema · Garden Shop Tables · suppliers, products, order_items, orders 4 tables
One row per supplier. Some suppliers have no contact email.
One row per product, with price, cost, and inventory levels.
One row per line item within an order.
One row per order. Unshipped orders have a null shipped_date.
Build a Top-5 supplier margin report for shipped orders. Return supplier_name, revenue, cost, gross_margin, and margin_pct. Round money to two decimals and margin_pct to one decimal. Rank by gross_margin descending, then supplier_name, and keep the top five.
Run your query to inspect the result.
Expected answer
- Columns: supplier_name, revenue, cost, gross_margin, margin_pct.
- Rows: the top 5 suppliers by gross margin.
- Sort by gross_margin descending, then supplier_name.
That's the last lesson in “Applied Practice: Store Operations.”
The next chapter builds on what this one covered.
Start Chapter 15: Set Operations → Begins with 15.1 UNION ALLRelated
COUNT, SUM, AVG, MIN, MAX, GROUP BY, and HAVING.
COUNT, SUM, AVG, GROUP BY, and HAVING.
Practice aggregate reports, HAVING, and answer shape.
Avoid truncating fractional results.
Group or aggregate every selected column.
Nested SELECTs, IN, EXISTS, and correlation.