SQL · Level 3 Window functions

SQL ROW_NUMBER() and the Latest Row

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

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

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.

Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.

orders 5 rows
idINTEGERcustomer_idINTEGERcreated_atTEXTtotalREAL
112024-01-0510.0
222024-01-0720.0
312024-03-0115.0
432024-02-025.0
522024-02-288.0
solution.sql
Test Suites Pending
Output