Function table / Table calculations / Running percent of total

Running percent of total, from Tableau to SQL

Measures cumulative revenue as a share of the full regional total. Below, 8 sample rows go through the calculation and through the SQL, and both return the same numbers.

Calculated field

RUNNING_SUM(SUM([Revenue])) / WINDOW_SUM(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((sum("Revenue") OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) / nullif(sum("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.166667
Harbor21801000.416667
Harbor31801200.666667
Harbor42401401
Upland190500.157895
Upland21501100.421053
Upland3null900.421053
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((sum("Revenue") OVER ( ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) / nullif(sum("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.0930233
    Harbor21801000.302326
    Harbor31801200.55814
    Harbor42401400.744186
    Upland190500.162791
    Upland21501100.418605
    Upland3null900.55814
    Upland43301901

    Matches the calculation

    SELECT CAST((sum("Revenue") OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) / nullif(sum("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.166667
    Harbor21801000.416667
    Harbor31801200.666667
    Harbor42401401
    Upland190500.157895
    Upland21501100.421053
    Upland3null900.421053
    Upland43301901

Signature

RUNNING_SUM(SUM([Revenue])) / WINDOW_SUM(SUM([Revenue]))