Best Usage of NTILE function in SQL Server and other RDBMSs

SQL Server NTILE() is a window function that distributes rows of an ordered partition right into a unique quantity of approximately same partition or group or buckets. The use of the function is described with a real time problem scenario. 

Problem Scenario: An agency is doing unique sort of promotional events on 1st of each month. The administration wanted to peer, which promotional event has benefited the organization in each region. 

USE dbTest

CREATE TABLE tbSalesSummary(
YearMonth INT,
SummaryMonth VARCHAR(20),
TotalSales DECIMAL(20,2));

INSERT INTO tbSalesSummary(YearMonth,SummaryMonth,TotalSales) VALUES
(201901, ‘January’, 339000),

The above code helps to create the table and insert the data to examine the behavior of NTILE function.

–To retrieve quarterly sales info
WITH CTE(Qtr, TotalSales) AS(
SELECT Qtr, MAX(TotalSales) FROM(
SELECT NTILE(4) OVER(ORDER BY YearMonth) Qtr, * FROM tbSalesSummary)
Results GROUP BY Qtr)

SELECT NTILE(4) OVER(ORDER BY YearMonth) Qtr, * FROM tbSalesSummary) S
ON CTE.Qtr = S.Qtr AND CTE.TotalSales = S.TotalSales

NTILE Example

If you look at the results, the maximum sales from every quarter has been retrieved. This function is available in most of the RDBMS applications along with Big Data technologies like Hive & Impala. The functionality and behavior is same. 

Hope you like this article.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s