22. Customers who cancelled and completed
Asked in screens shaped like: Stripe, Adyen, Checkout.com
Risk wants customers who both cancelled at least one order and completed at least one order. Return customer_id, cancelled_orders, and completed_orders, smallest customer_id first.
Requirements
- Columns: customer_id, cancelled_orders, completed_orders
- Keep customers with at least one cancelled and one completed order
- Order by customer_id
Expected output
customer_id, cancelled_orders, completed_orders
Row order is graded, so ORDER BY matters here.
Tables this problem reads. The full warehouse is available in thesandbox.
orders
~200 rows
Order headers. One row per order, so amount is the order total — not a line total.
- order_idINTEGER— 1000–1199
- customer_idTEXT— C01–C12
- countryTEXT— US, DE, IN, UK, BR
- amountREAL
- statusTEXT— 'completed' or 'cancelled'
- ordered_atTEXT— YYYY-MM-DD HH:MM:SS
Pick a warehouse dialect above the editor. The engine is still SQLite; common syntax is rewritten before it runs.
SQLite cheat sheet
- Truncate to day
DATE(ordered_at) - Current date
DATE('now') - Conditional
CASE WHEN … THEN … ELSE … END - String aggregate
GROUP_CONCAT(col, ", ") - JSON field
json_extract(payload, '$.source') - Date difference
JULIANDAY(a) - JULIANDAY(b) - Filter a window
CTE, then WHERE rn = 1 - Median
ROW_NUMBER + COUNT(*) OVER ()
Revealed one at a time. The reference query stays in the Solution tab.
Hint 1
GROUP BY customer_id with two conditional counts.
Hint 2
HAVING SUM(status = 'cancelled') >= 1 AND SUM(status = 'completed') >= 1 — SQLite treats true as 1.
SELECT customer_id,
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled_orders,
SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) AS completed_orders
FROM orders
GROUP BY customer_id
HAVING SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) >= 1
AND SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) >= 1
ORDER BY customer_id;Why it works
Two facts about the same customer is a HAVING, not two queries glued in the app. Conditional SUM keeps grain at customer_id without a self-join.
Run your query to see the result set.
Submit to run the checks.
Why it works
Two facts about the same customer is a HAVING, not two queries glued in the app. Conditional SUM keeps grain at customer_id without a self-join.
Pro problem
Hard problems unlock with Pro
Easy pads stay free. Medium and hard SQL and Python problems — editor, tests, hints, and solutions — open after you upgrade to Pro or coaching.
See plansPractice free easy problems