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.
CREATE TABLE tbSalesSummary(
Id INT IDENTITY(1,1),
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 S.* FROM CTE
SELECT NTILE(4) OVER(ORDER BY YearMonth) Qtr, * FROM tbSalesSummary) S
ON CTE.Qtr = S.Qtr AND CTE.TotalSales = S.TotalSales
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.