SQL Tips by Namwar Rizvi

June 20, 2007

Ranking in TSQL by RANK,DENSE_RANK and Row_Number

Filed under: Information,New Features,Query,Row_Number,SQL Server 2005,TSQL — namwar @ 10:31 PM

Ranking of results has many benefits and it is used in several scenarios of TSQL. Most common example of ranking is to ranking Sales person by their sales. This type of ranking requires you to assign same rank to all those Sales persons who generated the same sales amount, this is called tie. SQL Server 2005 provides you easy and efficient ways for different types of ranking requirements. There are four ranking functions in SQL Server 2005:

  1. RANK
  2. Dense_Rank
  3. Row_Number
  4. NTILE

NTILE is actually little bit different and it is used to assign a so called batch numbers or group numbers to the given result.

Following example will help you to understand Row_Number,RANK and Dense_Rank function which are mostly used in Ranking. For the detailed discussion of Ranking functions, please visit SQL Server Books Online

–Turn off intermediate messages
Set Nocount On

–Create a table variable
Declare @mTestTable table
(
id int,
city varchar(50)

)

–Insert some sample data
Insert into @mTestTable values (1,‘London’)
Insert into @mTestTable values (2,‘Karachi’)
Insert into @mTestTable values (3,‘New York’)
Insert into @mTestTable values (2,‘Paris’)

—Execute the query to compare Row_Number,Rank and Dense_Rank function
Select Id,city,
Row_Number() OVER (Order by id) as RowNumber,
Rank() OVER (Order by id) as RankNumber,
Dense_Rank() OVER (Order by id) as DenseRankNumber
from @mTestTable order by id

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: