20. Median completed order amount
Asked in screens shaped like: Capital One, JPMorgan, Robinhood
Report the median completed order amount without a percentile function. The median is the middle value for an odd count and the average of the two middle values for an even count, so the solution has to handle both.
Requirements
- Columns: median_amount
- Only status = 'completed'
- Exactly one row
- median_amount rounded to 2 decimals
Expected output
median_amount
Row order is not graded on this problem.
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
Number the rows by amount and get the total count in the same CTE.
Hint 2
COUNT(*) OVER () gives the row count without a second scan.
Hint 3
Rows (n+1)/2 and (n+2)/2 with integer division select the middle one or two rows.
WITH ranked AS (
SELECT amount,
ROW_NUMBER() OVER (ORDER BY amount) AS rn,
COUNT(*) OVER () AS n
FROM orders
WHERE status = 'completed'
)
SELECT ROUND(AVG(amount), 2) AS median_amount
FROM ranked
WHERE rn IN ((n + 1) / 2, (n + 2) / 2);Why it works
For odd n both expressions land on the same row and AVG returns it unchanged; for even n they pick the two middle rows and AVG splits them. Warehouses expose PERCENTILE_CONT(0.5), but interviewers ask for the manual version to test frame reasoning.
Run your query to see the result set.
Submit to run the checks.
Why it works
For odd n both expressions land on the same row and AVG returns it unchanged; for even n they pick the two middle rows and AVG splits them. Warehouses expose PERCENTILE_CONT(0.5), but interviewers ask for the manual version to test frame reasoning.
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