The RANK() function is a window function could be used in SQL Server to calculate a rank for each row within a partition of a result set.
The same rank is assigned to the rows in a partition which have the same values. The rank of the first row is 1. The ranks may not be consecutive in the RANK() function as it adds the number of repeated rows to the repeated rank to calculate the rank of the next row.
Syntax :
RANK() OVER ( [PARTITION BY expression, ] ORDER BY expression (ASC | DESC) );
Example –
Let us create a table geek_demo that has only column Name :
CREATE TABLE geek_demo (Name VARCHAR(10) );
Now, insert some rows into the sales.rank_demo table :
INSERT INTO geek_demo (Name)
VALUES('A'), ('B'), ('B'), ('C'), ('C'), ('D'), ('E');
Select data from the geek_demo table :
SELECT * FROM sales.geek_demo;
| Name |
|---|
| A |
| B |
| B |
| C |
| C |
| D |
| E |
Let us use RANK() to assign ranks to the rows in the result set of geek_demo table :
SELECT Name, RANK () OVER ( ORDER BY Name ) AS Rank_no FROM geek_demo;
Output –
| Name | Rank_no |
|---|---|
| A | 1 |
| B | 2 |
| B | 2 |
| C | 4 |
| C | 4 |
| D | 6 |
| E | 7 |
Recommended Posts:
- Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
- SQL Server | STUFF() Function
- SQL Server LAG() function Overview
- SIN() and COS() Function in SQL Server
- SQL Server LEAD() function Overview
- NTILE() Function in SQL Server
- STR() Function in SQL Server
- UNICODE() Function in SQL Server
- SUBSTRING() Function in SQL Server
- RTRIM() Function in SQL Server
- FLOOR() and CEILING() Function in SQL Server
- TAN() and COT() Function in SQL Server
- DEGREES() and RADIANS() Function in SQL Server
- ATN2() Function in SQL Server
- LOG10() Function in SQL Server
- LOG() Function in SQL Server
- ASCII() Function in SQL Server
- DIFFERENCE() Function in SQL Server
- IIF() Function in SQL Server
- Delete statement in MS SQL Server
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : khushboogoyal499

