TopicsCheat sheetLessons
Lurndo › Topics › Windows per group with PARTITION BY

Learn SQL: Windows per group with PARTITION BY

Per team, per stage

Every team wants its own little list: who is our youngest, who is our best rider per stage? "Four teams, five stages. That's a lot of lists," sighs Griet. Or one query that starts counting again for each group.

Starting again per group

With PARTITION BY inside the OVER you split the rows into groups. The window function starts again in each group: here the youngest rider of every team gets number 1.

Unlike with GROUP BY, all rows stay. So you don't get four rows but sixteen, each with a number within its own team.

SELECT r.name, t.name AS team, r.birth_date, ROW_NUMBER() OVER (PARTITION BY r.team_id ORDER BY r.birth_date DESC) AS num FROM riders r JOIN teams t ON t.id = r.team_id
Result
nameteambirth_datenum
Milan DhondtFlandrien Pro2003-01-301
Wout De ClercqFlandrien Pro2001-07-022
Lars VermeulenFlandrien Pro1999-03-143
Jens MoreelsFlandrien Pro1997-11-234
Tibo LauwersPajot Cycling2002-09-171
Arne Van HeckePajot Cycling2000-05-092
Senne PauwelsPajot Cycling1998-12-053
Kasper HolmPajot Cycling1996-04-214

The best per group

A classic: the best row per group. Number per group first in a WITH, then keep only number 1.

PARTITION BY can take several columns too. Here you see, per stage, the best placed rider of each team: five stages, four teams, twenty rows.

WITH ranked AS (
SELECT res.stage_id, r.team_id, r.name, res.position,
ROW_NUMBER() OVER (PARTITION BY res.stage_id, r.team_id ORDER BY res.position) AS num
FROM results res JOIN riders r ON r.id = res.rider_id
)
SELECT stage_id, team_id, name, position FROM ranked WHERE num = 1
Result
stage_idteam_idnameposition
11Wout De Clercq10
12Arne Van Hecke6
13Ruben de Graaf2
14Louis Garnier1
21Jens Moreels3
22Tibo Lauwers5
23Jesper Kuipers1
24Hugo Lefèvre4

Try it yourself

Number the riders per team, the oldest gets 1. Show the name, the team_id and the number.

Ready for more?

The full lesson has 5 exercises, from easy to challenging, with hints, points and a streak you can build.

Start the lesson
← PreviousSame timeNext →The standings
SQL topicsCheat sheetExcelLeaderboardAccountPrivacyNederlands