NTILE
The NTILE() window function returns grouping of approximately equals rows of data into buckets numbered
numerically. It is a useful function to put data into seperate buckets based on specifications provided on the
OVER() clause. We determine the number of buckets by passing an integer value into the NTILE() function.
NTILE by Example
Suppose we have a table with employees data include employee_id and salary and we
are interested in bucketing the information into similar ranges of compensation. We can use the NTILE() to
achieve this, grouping similar salaries into buckets
Here is an example implementation:
SELECT
employee_id,
last_name,
salary,
NTILE(10) OVER(ORDER BY salary DESC) as salary_buckets
FROM employees
WHERE is_active = TRUE and salary IS NOT NULL;
Observing the buckets, you can naturally see the query returns a combintion of employees whose compensation largely are in the same category.
This can be taken step further by adding a partition by clause by department for example. Notice that the input to NTILE() is an arbitrary
number and therefore some thought should always be used to do this sort of bucketing.