RFM Quintile Scores With NTILE
Score customers into quintiles with three NTILE windows over recency, frequency, and spend, then concatenate the ranks into a classic RFM score string.
Code
-- RFM: bucket customers into quintiles by recency (R), frequency (F), and money (M)
-- Three NTILE(5) windows rank each dimension, then concatenate into a combined 1-5 score
WITH orders (customer_id, ordered_at, amount_cents) AS (
VALUES
(1, timestamptz '2026-06-10', 42000), (1, timestamptz '2026-11-01', 15000),
(2, timestamptz '2026-11-15', 99000), (2, timestamptz '2026-11-16', 3000),
(3, timestamptz '2026-03-02', 5000), (3, timestamptz '2026-04-01', 5000),
(4, timestamptz '2026-11-17', 70000),
(5, timestamptz '2026-08-20', 12000), (5, timestamptz '2026-10-11', 22000)
),
per_customer AS (
SELECT customer_id,
MAX(ordered_at) AS last_order,
COUNT(*) AS order_count,
SUM(amount_cents) AS spend
FROM orders
GROUP BY customer_id
),
scored AS (
SELECT customer_id,
-- R must score "more recent = higher": NTILE ranks ascending, so the newest dates need DESC to land in bucket 5
NTILE(5) OVER (ORDER BY last_order DESC) AS r,
NTILE(5) OVER (ORDER BY order_count DESC) AS f,
NTILE(5) OVER (ORDER BY spend DESC) AS m
FROM per_customer
)
-- r/f/m come back as integers, and Postgres only defines || when at least one
-- side is a string, so cast each rank to text before concatenating
SELECT customer_id, r::text || f::text || m::text AS rfm_score
FROM scored
ORDER BY rfm_score DESC, customer_id;Inside the snippet
The statement is SELECT, touching orders, per_customer and scored.
Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; COUNT, SUM, MAX aggregation; a GROUP BY that collapses matching rows into one output row per group; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
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.
Putting it to use
Point it at the orders table.
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
- Name the tables involved in this file.
- `orders`, `per_customer`, `scored`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.