Tuesday, 16 June 2015

Rank, Dense_Rank and Row_Number



RANK()

Returns the rank of each row in the result set of partitioned column.
select Name,Subject,Marks,
RANK() over(partition by name order by Marks desc)Rank
From ExamResult
order by name,subject

Rank() Example

DENSE_RANK()

This is same as RANK() function. Only difference is returns rank without gaps.
select  Name,Subject,Marks,
DENSE_RANK() over(partition by name order by Marks desc)Rank
From ExamResult
order by name

DENSE_RANK() Example
In RANK() result set screenshot, you can notice that there is gap in Rank(2) for the name Sam and same gap is removed in DENSE_RANK().

NTILE()

Distributes the rows in an ordered partition into a specified number of groups.
It divides the partitioned result set into specified number of groups in an order.

Example for NTILE(2)

select Name,Subject,Marks,
NTILE(2) over(partition by name order by Marks desc)Quartile
From ExamResult
order by name,subject

NTILE(2) Example

Example for NTILE(3)

select Name,Subject,Marks,
NTILE(3) over(partition by name order by Marks desc)Quartile
From ExamResult
order by name,subject

NTILE(3) Example

ROW_NUMBER()

Returns the serial number of the row order by specified column.
select Name,Subject,Marks,
ROW_NUMBER() over(order by Name) RowNumber
From ExamResult
order by name,subject
 ROW_NUMBER() Example

No comments:

Post a Comment