PERCENT_RANK()
Overview
PERCENT_RANK()
window function determines the relative rank of a value in a group of values, based on the ORDER BY
expression in the OVER
clause. It can be used with all data types supported by Oxla.
Syntax
The syntax for this function is as follows:
The PERCENT_RANK()
is calculated as:
Where r
is the rank of the current row and n
is the total number of rows in the window or partition.
Rows with equal values for the ranking criteria receive the same relative rank. The output data type for this function is DOUBLE PRECISION
. The output will indicate the rank of values in a table, regardless of the input types.
- If the optional
PARTITION BY
expression is present, the rankings are reset for each group of rows - If the
ORDER BY
expression is omitted then all relative ranks are equal to 0
Parameters
()
: this function takes no arguments but parentheses is requiredPARTITION BY
: optional clause used to divide the result set into partitions (PERCENT_RANK()
function is applied to each partition independently)ORDER BY
: order of rows in each partition to which the function is applied
Examples
For the needs of this section, we will create the winsales
table that stores details about some sales transactions:
PERCENT_RANK() with ORDER BY
In this example, we will focus on executing the PERCENT_RANK()
function with ORDER BY
keyword and calculate the descending percent rank of all rows based on the quantity sold:
Here is the output for the query presented above that includes the sales ID along with the quantity sold and both percent and regular ranks:
PERCENT_RANK() with ORDER BY and PARTITION BY
In this example, we will focus on executing the PERCENT_RANK()
function with ORDER BY
keyword and PARTITION BY
clause, partition the table by seller ID, order each partition by the quantity and assign a percent rank to each row:
Here is the output for the query presented above: