Brightlane's finance team wants a single-row summary covering two figures:
- The combined revenue from delivered orders (
status = 'delivered'). - The combined revenue from cancelled orders (
status = 'cancelled').
Write a query to return both totals in a single row.
Assumptions:
- The
orderstable contains every order Brightlane has processed. - Both totals come from the same scan of the
orderstable — noWHEREclause restricts rows out, because both buckets are needed in the same row.
Output:
- A single row with two columns,
delivered_revenueandcancelled_revenue.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
SUM(
CASE
WHEN status = 'delivered' THEN total_amount
END
) AS delivered_revenue,
SUM(
CASE
WHEN status = 'cancelled' THEN total_amount
END
) AS cancelled_revenue
FROM
orders The shape
Two SUM(CASE WHEN ...) expressions route each row's total_amount into the bucket that matches its status. Delivered orders feed delivered_revenue; cancelled orders feed cancelled_revenue; everything else falls out as NULL and is skipped by SUM. One pass, two totals: 104331.81 and 6147.96.
Clause by clause
SUM(CASE WHEN status = 'delivered' THEN total_amount END) AS delivered_revenueevaluates theCASEonce per row. When the row'sstatusis'delivered', the expression returns that row'stotal_amount; otherwise theCASEfalls through with noELSEand returnsNULL.SUMskips theNULLs and totals only the delivered amounts.SUM(CASE WHEN status = 'cancelled' THEN total_amount END) AS cancelled_revenuedoes the same on a different predicate. The same row that contributed to the delivered column contributesNULLhere, so the two columns tally disjoint slices in the same pass.FROM ordersis the source. There is noWHEREand noGROUP BY: theCASEinside each aggregate does the filtering work that aWHEREwould have done on a single-bucket query.
You practiced conditional aggregation: SUM(CASE WHEN ... THEN col END). The recurring shape: each CASE returns the value for matching rows and NULL for the rest; SUM ignores NULLs, so each aggregate sums only its matching slice — multiple buckets in one query, one pass over the data.