Rank means: ‘Placing things by merit/grades/preference and assigning a number to it‘
The T-SQL ranking functions ROW_NUMBER(), RANK() and DENSE_RANK() were introduced for ranking of rows in SQL Server 2005.
There syntax is as following:
ROW_NUMBER () OVER ([<partition_by_clause>] <order_by_clause>)
Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.
Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.
RANK () OVER ([<partition_by_clause>] <order_by_clause>)
Returns the rank of each row within the partition of a result set.
Returns the rank of each row within the partition of a result set.
DENSE_RANK () OVER ([<partition_by_clause>] <order_by_clause>)
Returns the rank of rows within the partition of a result set, without any gaps in the ranking.
Returns the rank of rows within the partition of a result set, without any gaps in the ranking.
note : only [<partition_by_clause>] is Optional, and everything else is mandatory.
So what is partition ranking ?
Suppose we want to rank employees in a company according to their salaries. Then a simple rank function will suffice. But what if i want this ranking to be done not in the whole company but in their department to find whose salary is greater than other employees in a Accounts Department. So here, the ‘Partition By‘ comes into picture, where the result set is divided into parts and then ranking is performed.
Example :
Create a simple table:
Insert values into this table :
Here i am using the following query to get the data for different ranking functions depending on the value of Total_Amt:
The result :
No comments:
Post a Comment