Sign in to run and submit your work
Reading is open to everyone. Running code and saving drafts need an account so your work is yours and comes back on your next visit.
or
CODE WORKSPACE
The pricing team keeps quoting the average order value, and a single 300 order is dragging it around. They want the median instead — the middle order for each customer. SQLite has no MEDIAN function, so it has to be built out of positions.
Return one row per customer, ordered by customer_id.
Result columns · in this order
customer_id | The customer. |
orders | How many orders they placed. |
median_order_total | Their median order value. |
How to approach it
Number each customer's orders by value, and get the count of them onto the same rows.
Sample input
| order_id | customer_id | placed_at | status | order_total |
|---|---|---|---|---|
| 1001 | c1 | 2026-01-05 10:00:00 | paid | 120 |
| 1002 | c2 | 2026-01-12 14:30:00 | Paid | 80 |
| 1003 | c1 | 2026-01-20 09:15:00 | pending | 45 |
| 1004 | c3 | 2026-01-31 23:30:00 | PAID | 200 |
| 1005 | c2 | 2026-02-01 00:15:00 | paid | 60 |
| 1006 | c4 | 2026-02-03 11:00:00 | paid | 150 |
| 1007 | c3 | 2026-02-10 16:45:00 | refunded | 90 |
| 1008 | c1 | 2026-02-14 12:00:00 | paid | 300 |
| 1009 | c5 | 2026-02-18 08:30:00 | Paid | 75 |
| 1010 | c4 | 2026-02-25 19:20:00 | pending | 85 |
| 1011 | c5 | 2026-02-28 21:00:00 | paid | 130 |
| 1012 | c2 | 2026-03-02 10:10:00 | paid | 95 |
12 rows — scroll inside the table to see them all.
Expected output
| customer_id | orders | median_order_total |
|---|---|---|
| c1 | 3 | 120 |
| c2 | 3 | 80 |
| c3 | 2 | 145 |
| c4 | 2 | 117.5 |
| c5 | 2 | 102.5 |
5 rows — all rows shown.
Constraints
order_total and take the middle one. With an even number of orders, take the average of the two middle values.c1 and c2 have 3 orders, c3, c4 and c5 have 2.median_order_total to 2 decimal places.customer_id.Worked example
c1's orders are 45, 120 and 300. The median is the middle value, 120, while the average is 155 — pulled upwards by one large order. That gap is the whole reason the pricing team asked.
c4 has only two orders, 85 and 150, so there is no single middle row and the median is their average: 117.5.
What this tests
Building an aggregate the engine does not provide, using ROW_NUMBER together with a partition-level COUNT to pick the middle row — or rows — arithmetically rather than by branching.
Submit for review to find out what your query gets right, what it gets wrong, and how it compares with the best working query for this exercise.
This scenario runs a full workspace — editor, canvas and results side by side. It needs a laptop or desktop to be usable. Open this page on a bigger screen to start building.