// SQL snippet

Deciles with NTILE

NTILE(10) is a decile: same row count per bucket, regardless of the amounts.

Main statement
All engines

The task

You want orders split into ten equal-count groups by amount so you can say 'this order is in the top decile'.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT customer_id, amount,
       NTILE(10) OVER (ORDER BY amount DESC) AS decile
FROM orders
ORDER BY decile, amount DESC;

仕組み

NTILE(10) numbers the buckets 1 to 10 over the amount ordering, filling each with as close to an equal row count as division allows; the first buckets absorb the remainder. Decile 1 is the most expensive tenth of orders because of the DESC sort. Ties straddle bucket boundaries, since NTILE counts rows, not distinct values.

Variations

Keep only the top decile

WITH banded AS (
  SELECT id, customer_id, amount,
         NTILE(10) OVER (ORDER BY amount DESC) AS decile
  FROM orders
)
SELECT id, customer_id, amount
FROM banded
WHERE decile = 1
ORDER BY amount DESC;

Questions that come up

How is NTILE different from a percentage rank?

NTILE assigns bucket numbers by row count, so bucket 1 always holds about 10% of rows no matter how close their values are. PERCENT_RANK and CUME_DIST assign values by position and handle ties, which is what you want when the percentile itself matters more than the bucket size.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.