![]() |
VOOZH | about |
In PostgreSQL, the PERCENT_RANK() function is used to evaluate the relative ranking of a value within a given set of values. This function is particularly useful for statistical analysis and reporting, providing insights into how values compare within a dataset.
From this article, we can better understand the PERCENT_RANK Function in PostgreSQL.
The syntax of the PERCENT_RANK() function:
PERCENT_RANK() OVER ( [PARTITION BY partition_expression, ... ] ORDER BY sort_expression [ASC | DESC], ... )
Let's analyze the above syntax:
Let us take a look at some of the examples of PERCENT_RANKFunction in PostgreSQL from this article.
First, create two tables named 'products' and 'product_groups':
The following statement uses the PERCENT_RANK() function to calculate the sales percentile of each employee in 2019.
Query:
SELECT name, amount, PERCENT_RANK() OVER ( ORDER BY amount ) FROM sales_stats WHERE year = 2019;
Output:
👁 ImageExplanation: This query calculates the percentile rank of each sales amount for the year 2019. The ORDER BY clause orders the sales amounts, and PERCENT_RANK() assigns a percentile rank between 0 and 1 to each amount.
The below statement uses the PERCENT_RANK() function to calculate the sales amount percentile by sales employees in both 2018 and 2019.
Query:
SELECT name, amount, PERCENT_RANK() OVER ( PARTITION BY year ORDER BY amount ) FROM sales_stats;
Output:
👁 ImageExplanation: This query partitions the data by year, calculating the percentile rank of sales amounts within each year. The PARTITION BY year clause ensures that the ranking is calculated separately for each year, providing a relative ranking within each partition.
- The PERCENT_RANK() function calculates the relative rank of a value within a partition, providing a value between 0 and 1.
- When there are ties in the values being ranked, PERCENT_RANK() assigns the same percentile rank to those rows.
- The PERCENT_RANK() function does not consider NULL values in its calculations. Rows with NULL values in the ORDER BY clause are ranked last.
- PERCENT_RANK() can be combined with other window functions like 'ROW_NUMBER()', 'RANK()', and 'DENSE_RANK()' to provide a more comprehensive analysis.