RANK_PERCENTILE: from Tableau to SQL

Ranks regional mark revenues with the documented tie rule and excludes null measures. Below, 8 sample rows go through the calculation and through the SQL, and both return the same numbers.

Calculated field

RANK_PERCENTILE(SUM([Revenue]))

Compute using: addressing Period; partitioning Region

Sample data

RegionPeriodRevenueCost
Harbor112070
Harbor2180100
Harbor3180120
Harbor4240140
Upland19050
Upland2150110
Upland3null90
Upland4330190

The same calculation as SQL

SELECT CAST((CASE WHEN "Revenue" IS NULL THEN NULL ELSE CASE WHEN count("Revenue") OVER (PARTITION BY "Region")=1 THEN 0 ELSE (rank() OVER (PARTITION BY "Region" ORDER BY "Revenue" ASC NULLS LAST) + count("Revenue") OVER (PARTITION BY "Region", "Revenue") - 2)::DOUBLE / (count("Revenue") OVER (PARTITION BY "Region")-1) END END) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"

Runs the example above.

Result

RegionPeriodRevenueCostresult
Harbor1120700
Harbor21801000.666667
Harbor31801200.666667
Harbor42401401
Upland190500
Upland21501100.5
Upland3null90null
Upland43301901

Same rows from the calculation and from the SQL in DuckDB.

Where a naive translation goes wrong

  • Omitting the region partition allows a calculation to consume marks from other regions.

    Naive SQL

    SELECT CAST((CASE WHEN "Revenue" IS NULL THEN NULL ELSE CASE WHEN count("Revenue") OVER ()=1 THEN 0 ELSE (rank() OVER ( ORDER BY "Revenue" ASC NULLS LAST) + count("Revenue") OVER (PARTITION BY "Revenue") - 2)::DOUBLE / (count("Revenue") OVER ()-1) END END) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"
    RegionPeriodRevenueCostresult
    Harbor1120700.166667
    Harbor21801000.666667
    Harbor31801200.666667
    Harbor42401400.833333
    Upland190500
    Upland21501100.333333
    Upland3null90null
    Upland43301901

    Matches the calculation

    SELECT CAST((CASE WHEN "Revenue" IS NULL THEN NULL ELSE CASE WHEN count("Revenue") OVER (PARTITION BY "Region")=1 THEN 0 ELSE (rank() OVER (PARTITION BY "Region" ORDER BY "Revenue" ASC NULLS LAST) + count("Revenue") OVER (PARTITION BY "Region", "Revenue") - 2)::DOUBLE / (count("Revenue") OVER (PARTITION BY "Region")-1) END END) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"
    RegionPeriodRevenueCostresult
    Harbor1120700
    Harbor21801000.666667
    Harbor31801200.666667
    Harbor42401401
    Upland190500
    Upland21501100.5
    Upland3null90null
    Upland43301901

Signature

RANK_PERCENTILE(expression, [order])