PERCENT_RANK
PERCENT_RANK is a window function in SQL that calculates the percentile rank of a row in a result set. It takes into account the position of the row relative to the total number of rows and returns a relative rank value between 0 and 1 inclusive.
PERCENT_RANK() OVER ([PARTITION BY partition_expression] ORDER BY sort_expression [ASC | DESC])
Example
Output
Explanation
In the given example, PERCENT_RANK
function is applied on the score
column in the Students
table. The function calculates the percentile rank for each student’s score. The percentile rank is a percentile score that ranges from 0 to 1. It represents the proportion of scores in a distribution that a specific score is greater than. For example, a percent rank of 0.75 means that 75% of the data is below this point.
PERCENT_RANK() OVER ( [ PARTITION BY value_expression , … [ n ] ] ORDER BY sort_expression [ COLLATE collation_name ] [ ASC | DESC ] , … [ n ] )
Example
Output
ID | Value | PercentRank |
---|---|---|
1 | 10 | 0.000 |
2 | 20 | 0.250 |
3 | 30 | 0.500 |
4 | 40 | 0.750 |
5 | 50 | 1.000 |
Explanation
The PERCENT_RANK() function is used to calculate the relative rank of each row in the “TestRank” table based on the ‘Value’. The ranking values are distributed over the interval 0 to 1. This function gives the percentage of values that are less than the current value in the total dataset. For example, the PercentRank for the row with Value ‘30’ is 0.500, meaning that 50% of the total Values are less than 30.
PERCENT_RANK() OVER ([PARTITION BY column_name] ORDER BY column_name)
Example
Output
Explanation
The PERCENT_RANK function is used to calculate the percentage rank of a specified value in a group of values. In the above example, PERCENT_RANK is used to compute the percentile rank of employees’ salaries within the employees
table. The lowest salary has a rank of 0 and the highest has a rank of 1. The PERCENT_RANK is then displayed in the third column of the output.