Skip to main content

Categories: Window

PERCENT_RANK

Returns the relative rank of the current row within its partition as a value between 0.0 and 1.0. Calculated as (rank - 1) / (number of rows in the partition - 1). Requires an ORDER BY clause in the OVER window specification.

Syntax​

PERCENT_RANK() OVER ( [PARTITION BY partition_expression] ORDER BY order_expression) → double​

  • partition_expression (optional): An expression that groups rows into partitions.
  • order_expression: An expression that specifies the order of the rows within each partition.

Examples

PERCENT_RANK example
SELECT "Category", 
"Descript",
"DayOfWeek",
PERCENT_RANK()
OVER (
PARTITION BY "Category"
ORDER BY "DayOfWeek")
FROM Samples."samples.dremio.com"."SF_incidents2016.json"
-- Category, Descript, DayOfWeek, EXPR$3
-- ARSON, ARSON, Friday, 0.0
-- ARSON, ARSON, Monday, 0.1368421052631579
Calculate the relative rank with tied values
SELECT val, PERCENT_RANK() OVER (ORDER BY val) FROM (VALUES (10), (20), (20), (30)) AS t(val)
-- 10, 0.0
-- 20, 0.3333333333333333
-- 20, 0.3333333333333333
-- 30, 1.0
Calculate the relative rank with a NULL value
SELECT name, PERCENT_RANK() OVER (ORDER BY name) FROM (VALUES ('Dremio'), (NULL), ('Cloud')) AS t(name)
-- Cloud, 0.0
-- Dremio, 0.5
-- null, 1.0
Compare PERCENT_RANK and CUME_DIST
SELECT val, CUME_DIST() OVER (ORDER BY val), PERCENT_RANK() OVER (ORDER BY val) FROM (VALUES (10), (20), (20), (30)) AS t(val)
-- 10, 0.25, 0.0
-- 20, 0.75, 0.3333333333333333
-- 20, 0.75, 0.3333333333333333
-- 30, 1.0, 1.0