RUNNING_SUM: from Tableau to SQL

Calculates sum over the current and preceding regional marks, excluding null revenues. Below, 8 sample rows go through the calculation and through the SQL, and both return the same numbers.

Calculated field

RUNNING_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)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"

Runs the example above.

Result

RegionPeriodRevenueCostresult
Harbor112070120
Harbor2180100300
Harbor3180120480
Harbor4240140720
Upland1905090
Upland2150110240
Upland3null90240
Upland4330190570

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((sum("Revenue") OVER ( ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"
    RegionPeriodRevenueCostresult
    Harbor112070120
    Harbor2180100390
    Harbor3180120720
    Harbor4240140960
    Upland19050210
    Upland2150110540
    Upland3null90720
    Upland43301901290

    Matches the calculation

    SELECT CAST((sum("Revenue") OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"
    RegionPeriodRevenueCostresult
    Harbor112070120
    Harbor2180100300
    Harbor3180120480
    Harbor4240140720
    Upland1905090
    Upland2150110240
    Upland3null90240
    Upland4330190570

Signature

RUNNING_SUM(expression)