Windows Ranking Functions / Ranking Functions in SQL
Ranking functions are used to assign a rank to each row within a partition of a result set. The rank is based on the values in one or more columns. The ranking functions include:
- ROW_NUMBER()
- RANK()
- DENSE_RANK()
- NTILE(n)
|
ROW_NUMBER():
Assigns a unique sequential integer to rows within a partition. |
RANK():
Assigns a rank to each row, with gaps for ties. |
|
NTILE(n):
Divides rows into buckets and assigns numbers. |
DENSE_RANK():
Similar to RANK() but without gaps in the sequence. |
The ranking functions are often used in conjunction with the OVER() clause to define the partitioning and ordering of the result set.
SELECT column1, column2, ...,
RANK() OVER (PARTITION BY column1 ORDER BY column2) AS rank_column
FROM table_name;
In this example, the RANK() function assigns a rank to each row within the partition defined by column1, ordered by column2.
No comments:
Post a Comment