Topics / 🔀 Pipelines & Data Engineering Patterns / 🏭 Level 33: Data Engineering Patterns

SQL exercise · about 5 minutes · free

Window Functions: Best Match Per Player

Window functions are the most-loved SQL feature in interviews and the engine behind 'keep the latest row' dedupe.

ROW_NUMBER() OVER (PARTITION BY x ORDER BY y DESC) numbers rows within each group. Keep number 1 to get the top row per group.

SELECT * FROM (
  SELECT player_id, id,
         ROW_NUMBER() OVER (PARTITION BY player_id ORDER BY score DESC) AS rn
  FROM matches
) WHERE rn = 1
Table. ROW_NUMBER() per player: player_id, id, score, rn; 1 | 2 | 900 | 1; 1 | 1 | 500 | 2; 2 | 3 | 1400 | 1; 2 | 4 | 1100 | 2; 3 | 5 | 2000 | 1; 3 | 6 | 700 | 2. Operation: WHERE rn = 1. Result best match: player_id, id; 1 | 2; 2 | 3; 3 | 5; … | …ROW_NUMBER() per playerplayer_ididscorern129001115002231400124110023520001367002best matchplayer_idid122335……WHERE rn = 1
Your quest: For each player, show player_id and the id of their highest-scoring match.
Starter code
-- use ROW_NUMBER() OVER (PARTITION BY ...)
-- Run this first to see the matches table, then change it to answer the task.
SELECT *
FROM matches
LIMIT 5;

Try it in your browser → Free. Sign in with Google to run it. Your code runs on your device.

In this level you'll learn:
More in Level 33: Data Engineering Patterns

Share on LinkedIn