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.
Code
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-levelWHEREwill 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What are the relations in play here?
- `region_sales`, `ranked`, `numbered`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.