CODE WORKSPACE

Readable revenue query

Write a multi-CTE query that returns country and revenue: paid/shipped orders, joined to the buyer's country (missing country labelled 'unknown'), summed per country. Order by revenue descending, then country ascending.

paid_orders → orders_with_country (join + COALESCE) → country_revenue (group + sum) → expose.

Sample input

ordersPaid/shipped orders, joined to buyer country in a middle CTE.
order_idbuyer_idstatustotal_amount
10011paid80
10041shipped220
10106paid640
10052paid540
10084shipped150
customersbuyer_id → country; buyer 2 has a NULL country (becomes unknown).
customer_idcountry
1US
2null
3GB
4IN
6GB

Expected output

Expected outputRevenue per country over paid/shipped orders, highest first. GB combines buyers 3 and 6.
countryrevenue
GB930
unknown650
US300
IN150

Constraints

Use named CTEs (e.g. paid_orders, orders_with_country, country_revenue). Join orders to customers on buyer_id, COALESCE(country, 'unknown'). Keep the final SELECT boring. Order by revenue DESC, country ASC.

Expected skills

Layered CTEs, a join, COALESCE, and a clean final projection.

SQL
Loading...

AI evaluation

Run the SQL query to inspect preview rows.