Learn SQL/Advanced/Window Functions/SQL Ranking Within Groups

SQL Ranking Within Groups

RANK, formalized as a pattern: combine it with PARTITION BY and every group gets its own independent 1st place.

What & Why

Add PARTITION BY to any ranking function and the ranking restarts at 1 for every group — this is the pattern behind almost every "top performer per team/region/category" question.

See How It Works

BUSINESS QUESTION

Marketing ranks campaigns by spend inside each channel.

idnamechannelspendstart_dateend_datestatustarget_segment
1Spring Launchgoogle_ads55000.002024-01-152024-03-31activesmb
2Retention Webinaremail45000.002024-02-102024-04-15activeenterprise
3Finance Retargetinglinkedin50000.002024-03-122024-05-31activeenterprise
4Enterprise Searchgoogle_ads60000.002024-04-012024-06-30activeenterprise
EXAMPLE QUERY
SELECT
  id AS campaign_id,
  name,
  channel,
  spend,
  RANK() OVER (PARTITION BY channel ORDER BY spend DESC) AS channel_rank
FROM marketing.campaigns
ORDER BY channel, channel_rank, campaign_id;
RESULT — campaign rank restarts by channel
campaign_idnamechannelspendchannel_rank
2Retention Webinaremail45000.001
4Enterprise Searchgoogle_ads60000.001
1Spring Launchgoogle_ads55000.002
3Finance Retargetinglinkedin50000.001

The two google_ads campaigns form the only multi-row partition.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario