Tag Archives: Ranking function Rank()

Ranking Function – Rank()

Rank()
The RANK function sequentially numbers a record set, but when two rows have the same order by value then they get the same ranking. Ranking value will be incremented by 1 for next un-matched row.

Syntax
RANK ( ) OVER ( [ ] )

Examples
CREATE TABLE Emp(
EmpName VARCHAR(9),
Age INT,
MaritalStatus char(1))

INSERT INTO Emp VALUES (‘Abhinav’,40,’S’)
INSERT INTO Emp VALUES (‘Dhvani’,20,’M’)
INSERT INTO Emp VALUES (‘Nehal’,20,’M’)
INSERT INTO Emp VALUES (‘Sunil’,95,’M’)
INSERT INTO Emp VALUES (‘Suvrendu’,40,’M’)
INSERT INTO Emp VALUES (‘Bill’,11,’S’)
INSERT INTO Emp VALUES (‘Ram’,100,’S’)
INSERT INTO Emp VALUES (‘Nirmal’,50,’S’)
INSERT INTO Emp VALUES (‘R’,30,’S’)

Query – I

SELECT RANK() OVER (ORDER BY Age) AS [Rank by Age],
EmpName,
Age
FROM Emp

Rank by Age EmpName Age
-------------------- --------- -----------
1 Bill 11
2 Dhvani 20
2 Nehal 20
4 R 30
5 Abhinav 40
5 Suvrendu 40
7 Nirmal 50
8 Sunil 95
9 Ram 100

(9 row(s) affected)


SELECT RANK() OVER (PARTITION BY MaritalStatus ORDER BY Age) AS [Partition by MaritalStatus],
EmpName,
Age,
MaritalStatus
FROM emp

Partition by MaritalStatus EmpName Age MaritalStatus
-------------------------- --------- ----------- -------------
1 Dhvani 20 M
1 Nehal 20 M
3 Suvrendu 40 M
4 Sunil 95 M
1 Bill 11 S
2 R 30 S
3 Abhinav 40 S
4 Nirmal 50 S
5 Ram 100 S

Advertisements