Tuesday, July 27, 2010

Ranking Functions in SQL server

Let’s add RANK function onto this query, you can see additional column ranking the data.
 For example:
 the  Account Id  of ' kingslin ' are assigned a rank of 1 as they are equal, the Account Id  of Bala are assigned the next rank, stalin the next, etc. This is a simple way of assiging a Account Id   by class or category depending on how we order the data - the rank value of 3 simply means that all data with this rank number is the same.
Here I have used Table name with schema name (Customer.ShippingAddress)
Customer is the schema name for that table.



 select
 RANK() over (order by s_Acc_id) as Rank
, ROW_NUMBER() over (order by s_Acc_id) as RowNumber
, s_Acc_id from Customer.ShippingAddress


1 1    kingslin
 2 2    Bala
 3 3    Rajesh
 4 4    varakulan
 5 5    stalin
5 6    stalin
5 7    stalin
5 8    stalin
 9 9    vasanth
9 10    vasanth

Here Stalin Accound Id has the same values generated by the RANK and ROW_NUMBER functions giving us a very simple way of deduplicating the data.
How its working
•    the 'order by' clauses are used to bring specific sorted list
•    the ROW_NUMBER function gives sequential numbers
•    the RANK function allocates a value to each block of data matching the order criteria

Create CTE table and filter rows

 with AlphaRank(Rank, RowNumber, s_Acc_id) as (
select
  RANK() over (order by s_Acc_id) as Rank
, ROW_NUMBER() over (order by s_Acc_id) as RowNumber
, s_Acc_id
from Customer.ShippingAddress
)
select s_Acc_id from AlphaRank where Rank=RowNumber

output is :

kingslin
Bala
Rajesh
varakulan
stalin
vasanth

No comments:

Post a Comment