This article is half-done without your Comment! *** Please share your thoughts via Comment ***
In this post, I am sharing the use of two functions of PostgreSQL which are PERCENT_RANK() and CUME_DIST().
Using these functions, we can calculate the Percent Rank and Cumulative Percent Rank of number column.
We know about the normal RANK(), which generates the rank of the number. But sometimes, it requires checking the percentage instead of rank.
Please check the below demonstration:
Create a sample table with data:
1 2 3 4 5 |
CREATE TABLE tbl_Numbers (ID INTEGER); INSERT INTO tbl_Numbers VALUES (1),(2),(3),(4),(5); |
Calculate the Percent rank and Cumulative Percent rank:
1 2 3 4 5 6 |
SELECT ID ,(PERCENT_RANK() OVER win)::numeric(10, 2) as PercentRank ,(CUME_DIST() OVER win)::numeric(10, 2) as CumulativeRank FROM tbl_Numbers WINDOW win AS (ORDER BY ID); |
The Result:
Leave a Reply