Function table / Table calculations / Regional mark position fraction

Regional mark position fraction, from Tableau to SQL

Divides the one-based addressed position by the regional mark count. Below, 8 sample rows go through the calculation and through the SQL, and both return the same numbers.

Calculated field

INDEX() / SIZE()

Compute using: addressing Period; partitioning Region

Sample data

RegionPeriodRevenueCost
Harbor112070
Harbor2180100
Harbor3180120
Harbor4240140
Upland19050
Upland2150110
Upland3null90
Upland4330190

The same calculation as SQL

SELECT CAST((row_number() OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)::DOUBLE / count(*) OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"

Runs the example above.

Result

RegionPeriodRevenueCostresult
Harbor1120700.25
Harbor21801000.5
Harbor31801200.75
Harbor42401401
Upland190500.25
Upland21501100.5
Upland3null900.75
Upland43301901

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

Where a naive translation goes wrong

  • An unpartitioned SQL window mixes independent regional calculation sequences.

    Naive SQL

    SELECT CAST((row_number() OVER ( ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)::DOUBLE / count(*) OVER ( ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"
    RegionPeriodRevenueCostresult
    Harbor1120700.125
    Harbor21801000.375
    Harbor31801200.625
    Harbor42401400.875
    Upland190500.25
    Upland21501100.5
    Upland3null900.75
    Upland43301901

    Matches the calculation

    SELECT CAST((row_number() OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)::DOUBLE / count(*) OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"
    RegionPeriodRevenueCostresult
    Harbor1120700.25
    Harbor21801000.5
    Harbor31801200.75
    Harbor42401401
    Upland190500.25
    Upland21501100.5
    Upland3null900.75
    Upland43301901

Signature

INDEX() / SIZE()