February 22, 2014

Group Results and Rank Them in SQL Server using NTILE




The SQL Server NTILE() function divides the result set into a specified number of even sized group (approximate division) and assigns a ranking value to these groups.

The NTILE() function is similar to other ranking functions like the RANK() and DENSE_RANK(), except that NTILE takes one parameter of type int/bigint that specifies the number of groups into which each partition must be divided.

Let us see an example. We will query the Products table of the Northwind database and divide it into 5 groups ordered by the UnitsInStock:

NTILE SQL Server

OUTPUT

NTILE SQL Server Demo

On running the query, the results are divided into 5 groups, but because the total number of rows (48) is not divisible by the number of groups (5), NTILE puts 10 rows in the first three group and the remaining two groups have 9 rows each.


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

0 Responses to "Group Results and Rank Them in SQL Server using NTILE"
 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions