SQL interview question: find the bugs in a revenue query
Problem
Shared data rulesThe dashboard shows more revenue than the bank statement. For each city and platform, find revenue from successful September 2026 payments for delivered orders. Also give the platform’s share of the city’s revenue.
Formula
revenue_share = revenue_usd / the whole city’s revenue
Query to fix
Fix it freeWITH city_revenue AS (
SELECT city,
SUM(amount_usd) AS city_revenue_usd
FROM orders
WHERE created_at >= '2026-09-01'
AND created_at < '2026-10-01'
GROUP BY city
)
SELECT o.city,
o.platform,
COUNT(*) AS orders,
SUM(p.amount_usd) AS revenue_usd,
ROUND(SUM(p.amount_usd)::numeric / MAX(cr.city_revenue_usd), 4) AS revenue_share
FROM payments AS p
JOIN orders AS o
ON o.order_id = p.order_id
JOIN city_revenue AS cr
ON cr.city = o.city
WHERE o.status = 'delivered'
AND p.paid_at >= '2026-09-01'
AND p.paid_at < '2026-10-01'
GROUP BY o.city, o.platform
Example
orders| order_id | created_at | status | city | platform | amount_usd | Row note |
|---|---|---|---|---|---|---|
| 801 | 2026-09-05 09:40 | delivered | Boston | ios | 24 | |
| 802 | 2026-09-10 14:40 | delivered | Boston | web | 16 | |
| 803 | 2026-09-14 09:40 | cancelled | Boston | android | 30 | ← not delivered — skipped |
| 804 | 2026-09-20 11:40 | delivered | New York | ios | 60 |
- Order 803: not delivered — skipped
payments| payment_id | order_id | paid_at | amount_usd | status | Row note |
|---|---|---|---|---|---|
| 1 | 801 | 2026-09-05 10:00 | 24 | failed | ← failed attempt — skipped |
| 2 | 801 | 2026-09-05 10:01 | 24 | success | |
| 3 | 802 | 2026-09-10 15:00 | 16 | success | |
| 4 | 803 | 2026-09-14 10:00 | 30 | refunded | ← refund — skipped |
| 5 | 804 | 2026-09-20 12:00 | 60 | success |
- Payment 1: failed attempt — skipped
- Payment 4: refund — skipped
| city | platform | orders | revenue_usd | revenue_share |
|---|---|---|---|---|
| Boston | ios | 1 | 24 | 0.6 |
| Boston | web | 1 | 16 | 0.4 |
| New York | ios | 1 | 60 | 1 |
Boston’s revenue is $24 + $16 = $40: ios gets 0.6 and web 0.4.
Output columns
orders- number of orders with a successful payment
Fix it free
Fix the query — code checks it on PostgreSQL in your browser. No sign-up needed.