Function table / Table calculations / Regional min-max normalization

Regional min-max normalization, from Tableau to SQL

Scales revenue between the regional minimum and maximum. Below, 8 sample rows go through the calculation and through the SQL, and both return the same numbers.

Calculated field

(SUM([Revenue]) - WINDOW_MIN(SUM([Revenue]))) / (WINDOW_MAX(SUM([Revenue])) - WINDOW_MIN(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((("Revenue" - min("Revenue") OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) / nullif(max("Revenue") OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)-min("Revenue") OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING),0)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"

Runs the example above.

Result

RegionPeriodRevenueCostresult
Harbor1120700
Harbor21801000.5
Harbor31801200.5
Harbor42401401
Upland190500
Upland21501100.25
Upland3null90null
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((("Revenue" - min("Revenue") OVER ( ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) / nullif(max("Revenue") OVER ( ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)-min("Revenue") OVER ( ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING),0)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"
    RegionPeriodRevenueCostresult
    Harbor1120700.125
    Harbor21801000.375
    Harbor31801200.375
    Harbor42401400.625
    Upland190500
    Upland21501100.25
    Upland3null90null
    Upland43301901

    Matches the calculation

    SELECT CAST((("Revenue" - min("Revenue") OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) / nullif(max("Revenue") OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)-min("Revenue") OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING),0)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"
    RegionPeriodRevenueCostresult
    Harbor1120700
    Harbor21801000.5
    Harbor31801200.5
    Harbor42401401
    Upland190500
    Upland21501100.25
    Upland3null90null
    Upland43301901

Signature

(SUM([Revenue]) - WINDOW_MIN(SUM([Revenue]))) / (WINDOW_MAX(SUM([Revenue])) - WINDOW_MIN(SUM([Revenue])))