ntile
Divides the ordered rows within a partition into a specified number of buckets (groups) of as equal a size as possible, and returns the bucket number that the current row belongs to. Buckets are numbered starting from 1. For each partition, the rows are assigned to buckets in order: if the number of rows is not divisible by the number of buckets, the earlier buckets receive one more row than the later ones.
Syntax
The argument buckets must be a constant positive integer.
An ORDER BY clause is required. The window frame must be the whole partition (ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING), which is also the default frame used when none is specified explicitly.
For more detail on window function syntax see: Window Functions - Syntax.
Returned value
- The bucket number of the current row within its partition. UInt64.
Example
The following example divides the players into four buckets ordered by descending salary.
Here there are seven rows and four buckets, so the first three buckets contain two rows each and the last bucket contains a single row.