Top N Per Group With Rank Ties

Keep every tie inside the top three per region with RANK() <= 3 over a PARTITION BY window, and contrast the truncating ROW_NUMBER version.

SqlData Integrity

Code

snippet
CREATE TABLE region_sales (
    id      int PRIMARY KEY,
    region  text NOT NULL,
    rep     text NOT NULL,
    revenue numeric NOT NULL
);

INSERT INTO region_sales VALUES
    (1, 'eu',  'ada', 1200),
    (2, 'eu',  'raj', 1200),   -- 与 ada 并列第一:RANK 会并列,ROW_NUMBER 会截断
    (3, 'eu',  'kim', 900),
    (4, 'na',  'lin', 2000),
    (5, 'na',  'bob', 700),
    (6, 'eu',  'eve', 900);    -- 与 kim 并列第三:并列组跨过 N=3 边界,RANK 版会返回 4 行

-- 每组取前三(含并列):RANK 允许同分并列,前三名可能超过 3 行
WITH ranked AS (
    SELECT region, rep, revenue,
           RANK() OVER (PARTITION BY region ORDER BY revenue DESC) AS rnk
    FROM region_sales
)
SELECT region, rep, revenue, rnk
FROM ranked
WHERE rnk <= 3
ORDER BY region, rnk, rep;

-- 对照:ROW_NUMBER 强制唯一序号,与 eve 并列第三的 kim 被硬截断丢掉
WITH numbered AS (
    SELECT region, rep, revenue,
           ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC, rep) AS rn
    FROM region_sales
)
SELECT region, rep, revenue, rn
FROM numbered
WHERE rn <= 3
ORDER BY region, rn;

How it works

The file runs SELECT / INSERT / CREATE statements, touching region_sales, ranked and numbered.

Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause constraining which rows the statement operates on; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

What to watch for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Applying it

The region_sales table is the working surface here.

Statements that matter

WITH numbered AS (
    SELECT region, rep, revenue,
           ROW_NUMBER() OVER (PARTITION BY region ORDER BY revenue DESC, rep) AS rn
    FROM region_sales
)
SELECT region, rep, revenue, rn
FROM numbered
WHERE rn <= 3
ORDER BY region, rn;
WITH ranked AS (
    SELECT region, rep, revenue,
           RANK() OVER (PARTITION BY region ORDER BY revenue DESC) AS rnk
    FROM region_sales
)
SELECT region, rep, revenue, rnk
FROM ranked
WHERE rnk <= 3
ORDER BY region, rnk, rep;
INSERT INTO region_sales VALUES
    (1, 'eu',  'ada', 1200),
    (2, 'eu',  'raj', 1200),   -- 与 ada 并列第一:RANK 会并列,ROW_NUMBER 会截断
    (3, 'eu',  'kim', 900),
    (4, 'na',  'lin', 2000),
    (5, 'na',  'bob', 700),
    (6, 'eu',  'eve', 900);    -- 与 kim 并列第三:并列组跨过 N=3 边界,RANK 版会返回 4 行

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`region_sales`, `ranked`, `numbered`.