The third stamp
- O(n²) · Very hard
- Full plan
- SQL
- window functions
- joins
- dates
Problem
The store is starting a stamp card: one stamp per order and, with the third stamp, a gift. Past orders count too, so some customers already have a full card. The owner wants to know which order filled each customer's card and how long it took.
A customer's orders go by date and, within the same day, by order number. Show four columns: the customer's name, the product their third order was for, that order's date, and the days that went by since their first one. Whoever filled the card in the fewest days goes on top, and ties go by name. Anyone with fewer than three orders isn't on the list.
The order dated the 20th is Luke's third, and it earns its stamp: until someone fixes the date, it's listed with the one it has on file.
What it has to return
These rows, in this order
| name | product | placed | days |
|---|---|---|---|
| Ann | Mouse | 2026-01-12 | 9 |
| Luke | Tablet | 2026-01-20 | 16 |
This is what comes out with the data in the practice database this challenge uses. The column names don’t count, so name yours however you like: what counts is how many there are and the order they come in. Besides this one, the challenge has hidden tests with other data that are revealed when you submit your solution.
You start with this
SQL
SELECT customer_id, placed,
ROW_NUMBER() OVER (
ORDER BY placed, id
) AS num
FROM orders;It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.
More O(n²) challenges
- The week of the 4thSQL · dates · grouping · strings
- What went out todaySQL · changing data · subqueries · nulls
- Which day do we close?SQL · dates · grouping · conditionals
- You started with a KeyboardSQL · window functions · joins
- A line for every daySQL · recursion · dates · window functions
- Arriving WednesdaySQL · dates · conditionals