You started with a Keyboard
- O(n²) · Very hard
- Full plan
- SQL
- window functions
- joins
Problem
The store wants to write each customer something that's about them: "You started with a Keyboard. The last thing you ordered was a Mouse."
For each customer who has ordered something, show three columns, in this order: their name, the product from their first order, and the product from their last. Sort alphabetically by customer. Someone who has ordered only once gets the same product in both columns.
Which order came first is decided by date and, within the same day, by order number. The one dated the 20th has a mistyped date, but whether it's the 15th or the 20th, it's the last thing Luke ordered, and it counts.
What it has to return
These rows, in this order
| customer | earliest | latest |
|---|---|---|
| Ann | Keyboard | Mouse |
| Chloë | Headphones | Headphones |
| Dylan | Laptop | Headphones |
| Luke | Mouse | Tablet |
| Mason | Cable | Cable |
| Valerie | Keyboard | Cable |
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 o.customer_id,
p.name AS product,
ROW_NUMBER() OVER (
PARTITION BY o.customer_id
ORDER BY o.placed, o.id
) AS num
FROM orders o
JOIN products p
ON o.product_id = p.id;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
- A line for every daySQL · recursion · dates · window functions
- Arriving WednesdaySQL · dates · conditionals
- Best day yetSQL · window functions · grouping · subqueries
- First with lastSQL · window functions · joins · grouping
- How soon they're backSQL · window functions · dates · grouping
- January off the shelfSQL · dates · nulls · grouping