Tuesday, 17 September 2013

RANKING Functions

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.
RANK () OVER ([<partition_by_clause>] <order_by_clause>)
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.
NTILE (integer_expression) OVER ([<partition_by_clause>] <order_by_clause>)
Distributes the rows in an ordered partition into a specified number of groups.

 EXAMPLES:
---------------
Suppose you are having table like below











Example :1
select ROW_NUMBER() over(order by salary)ROW_NUMBER,RANK()over(order by salary)
RANK,DENSE_RANK() over(order bysalary)DENSE_RANK,* from emp

Example :2
select ROW_NUMBER()over (order by empname)ROW_NUMBER,RANK()over (order byempname)RANK,DENSE_RANK()over (order by empname)DENSE_RANK,* from emp

Example :3
select ROW_NUMBER()over(partition by empname order by salary)ROW_NUMBER,RANK()
over(partitionby empname order by salary)RANK,DENSE_RANK()over(partition by
 empname order bysalary)DENSE_RANK,* from emp

Example :4
select ROW_NUMBER()over(partition by salary order by empname)ROW_NUMBER,RANK()
over(partitionby salary order by empname)RANK,DENSE_RANK()over(partition by 
salary order byempname)DENSE_RANK,* from emp

Example :5
select ROW_NUMBER()over(partition by empname order by empname)ROW_NUMBER,RANK()
over(partitionby empname order by empname)RANK,DENSE_RANK()
over(partition by empname order byempname)DENSE_RANK,* from emp

Example :6
select ROW_NUMBER()over(partition by salary order by salary)
ROW_NUMBER,RANK()over(partitionby salary order by salary)
RANK,DENSE_RANK()over(partition by salary order bysalary)
DENSE_RANK,* from emp

No comments:

Post a Comment

EMP, DEPT Sample script

/****** Object:  Table [dbo].[DEPT]    Script Date: 19-05-2016 06:58:37 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET A...