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.

SqlData Fetching

Code

snippet
-- 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-level WHERE will 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

FAQ

What are the relations in play here?
The references are `spend`.