Hypothetical Set Rank Within Group
rank(8.00) WITHIN GROUP inserts a would-be value into each ordering and reports its rank directly — the same semantics as a window rank without a frame.
Code
-- 假设集聚合(hypothetical-set):把一个"假如存在"的值插进排序列,直接问名次
CREATE TABLE leaderboard (
region text NOT NULL,
player text NOT NULL,
score numeric(6,2) NOT NULL
);
INSERT INTO leaderboard VALUES
('eu', 'ada', 9.50), ('eu', 'grace', 8.20),
('us', 'linus', 7.70), ('us', 'alan', 6.10);
-- 每个赛区各自算一次假设名次:8.00 在 eu 排第 3,在 us 排第 1
SELECT region,
rank(8.00) WITHIN GROUP (ORDER BY score DESC) AS would_be_rank
FROM leaderboard
GROUP BY region;
-- 全局口径:9.50 与 8.20 都在 8.00 之前,假设名次为 3
SELECT rank(8.00) WITHIN GROUP (ORDER BY score DESC) FROM leaderboard;What the code does
The file runs SELECT / INSERT / CREATE statements, touching leaderboard.
Breaking the statements into their working parts: a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.
Applying it
Run the statement against the leaderboard table.
Statements that matter
SELECT region,
rank(8.00) WITHIN GROUP (ORDER BY score DESC) AS would_be_rank
FROM leaderboard
GROUP BY region;
INSERT INTO leaderboard VALUES
('eu', 'ada', 9.50), ('eu', 'grace', 8.20),
('us', 'linus', 7.70), ('us', 'alan', 6.10);
CREATE TABLE leaderboard (
region text NOT NULL,
player text NOT NULL,
score numeric(6,2) NOT NULL
);
Interactive Tools for This Topic
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.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.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
- Which tables does this file reference?
- `leaderboard` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.