Lessons › SQL › Deep Dive: Advanced Window Functions
SQL lesson
NTILE() for ranking into equal buckets
NTILE splits rows into a set number of equal-sized groups and stamps each row with a group number based on its position in the sorted order - no manual cutoffs needed.
Try this lesson free →Example
Splitting rows into equal-sized buckets
SELECT name, total_spend, NTILE(3) OVER (ORDER BY total_spend) AS tier FROM customers| name | total_spend | tier |
|---|---|---|
| Sam Rivera | 320.75 | 1 |
| Tomas Klein | 890.0 | 1 |
| Jordan Lee | 1240.5 | 2 |
| Riya Mehta | 2870.1 | 2 |
| Min Chen | 3215.25 | 3 |
| Alex Park | 4890.0 | 3 |
Step by step
- AS gives a column a friendlier name in the result.
SELECT name, total_spend, NTILE(3) OVER (ORDER BY total_spend) AS tier - FROM tells SQL which table to pull the data from.
SELECT name, total_spend, NTILE(3) OVER (ORDER BY total_spend) AS tier FROM customers;
Practice
1. Write a query on the orders table that splits rows into 10 equal-sized buckets based on revenue, using NTILE. Return the revenue column and a column called revenue_bucket with the bucket number.
SELECT revenue, NTILE(10) OVER (ORDER BY revenue) AS revenue_bucket FROM orders2. Write a query on the store_sales table that splits rows into 4 equal-sized buckets based on revenue, using NTILE. Return the revenue column and a column called revenue_bucket with the bucket number.
SELECT revenue, NTILE(4) OVER (ORDER BY revenue) AS revenue_bucket FROM store_sales3. Write a query on the products table that splits rows into 5 equal-sized buckets based on price, using NTILE. Return the price column and a column called price_bucket with the bucket number.
SELECT price, NTILE(5) OVER (ORDER BY price) AS price_bucket FROM products4. Write a query on the employees table that splits rows into 5 equal-sized buckets based on salary, using NTILE. Return the salary column and a column called salary_bucket with the bucket number.
SELECT salary, NTILE(5) OVER (ORDER BY salary) AS salary_bucket FROM employees5. Write a query on the reviews table that splits rows into 4 equal-sized buckets based on rating, using NTILE. Return the rating column and a column called rating_bucket with the bucket number.
SELECT rating, NTILE(4) OVER (ORDER BY rating) AS rating_bucket FROM reviewsLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →