NTILE Bucketing Ordered Rows
Split ordered rows into near-equal buckets with NTILE(3) and NTILE(4); add a tiebreaker so equal keys land in stable buckets.
Code
-- NTILE(N) 把 ORDER BY 后的行尽量均分成 N 个桶:除不尽时靠前的桶各多一行
WITH spend AS (
SELECT * FROM (VALUES
('ada', 980),
('grace', 870),
('linus', 640),
('margaret', 520),
('alan', 350),
('barbara', 210),
('karl', 90)
) AS t(customer, cents)
)
SELECT
customer,
cents,
NTILE(3) OVER (ORDER BY cents DESC, customer) AS spend_tier,
NTILE(4) OVER (ORDER BY cents DESC, customer) AS quartile
FROM spend
ORDER BY cents DESC, customer;How it works
At its core this is a single SELECT statement against spend.
The pieces that do the work: a CTE (WITH … AS) that names an intermediate result before the main query; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
Watch out 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.
Putting it to use
Run the statement against the spend table.
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?
- The references are `spend`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.