The ntile()
window function distributes the rows evenly into n
groups.
SELECT ntile(3) OVER (ORDER BY …)
FROM …
The example returns 1 for the first third of the rows, 2 for the second and 3 for the last.
Similar functions: width_bucket()
.
The ntile()
window function is defined in ISO/IEC 9075:2016-2 as optional feature T614, “NTILE function”.
The essence of SQL tuning in 200 pages
Buy now!
(paperback and/or PDF)
Paperback also available at Amazon.com.
Markus offers SQL training and consulting for developers working at companies of any size.
Learn more »