CODE WORKSPACE

Paid order CTE decomposition

Using a CTE for paid or shipped orders, return buyer_id and revenue (the summed total_amount per buyer). Order by revenue descending, then buyer_id ascending.

Start with a paid_orders CTE, then a buyer_revenue CTE that groups it, then expose the result.

Sample input

ordersPaid/shipped orders feed the metric; pending/refunded are filtered out in the first CTE.
order_idbuyer_idstatustotal_amount
10011paid80
10041shipped220
10091pending30
10052paid540
10106paid640

Expected output

Expected outputRevenue per buyer over paid/shipped orders only (buyer 1 is 300, not 330). Highest first.
buyer_idrevenue
2650
6640
1300
3290
4150

Constraints

Use at least one CTE. The first layer filters status IN ('paid', 'shipped'); the second aggregates SUM(total_amount) per buyer. Order by revenue DESC, buyer_id ASC.

Expected skills

CTE decomposition, grouped aggregation, and readable intermediate naming.

SQL
Loading...

AI evaluation

Run the SQL query to inspect preview rows.