Overview
Pick each customer's most recent order with ROW_NUMBER() OVER (PARTITION BY ...), and filter it in a CTE since WHERE can't see window functions.
- ROW_NUMBER() OVER (...)
- PARTITION BY and ORDER BY
- Filter window results in a CTE
Short Course
A window function computes over a group of rows without collapsing them:
ROW_NUMBER() OVER (PARTITION BY team ORDER BY score DESC) numbers each
team's rows, best first. Trap: WHERE can't use a window function, so wrap
the query in a CTE and filter that.
WITH ranked AS (
SELECT name, team,
ROW_NUMBER() OVER (PARTITION BY team ORDER BY score DESC) AS rn
FROM players
)
SELECT team, name FROM ranked WHERE rn = 1; -- best player per team
Task
Return each customer's most recent order: customer_id, the order id and
its created_at, ordered by customer_id. In the database below, customer
1's latest order is id 3.
Database
Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.
| idINTEGER | customer_idINTEGER | created_atTEXT | totalREAL |
|---|---|---|---|
| 1 | 1 | 2024-01-05 | 10.0 |
| 2 | 2 | 2024-01-07 | 20.0 |
| 3 | 1 | 2024-03-01 | 15.0 |
| 4 | 3 | 2024-02-02 | 5.0 |
| 5 | 2 | 2024-02-28 | 8.0 |
Test Suites
Pending
Next
Output