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.

SqlData Integrity

Code

snippet
-- 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-level WHERE will not work — use an outer query or a CTE.

Putting it to use

Point it at the orders table.

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`orders`, `per_customer`, `scored`.