WINDOW_AVG: from Tableau to SQL

Calculates avg over all 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

WINDOW_AVG(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((avg("Revenue") 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
Harbor112070180
Harbor2180100180
Harbor3180120180
Harbor4240140180
Upland19050190
Upland2150110190
Upland3null90190
Upland4330190190

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((avg("Revenue") OVER ( ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"
    RegionPeriodRevenueCostresult
    Harbor112070184.286
    Harbor2180100184.286
    Harbor3180120184.286
    Harbor4240140184.286
    Upland19050184.286
    Upland2150110184.286
    Upland3null90184.286
    Upland4330190184.286

    Matches the calculation

    SELECT CAST((avg("Revenue") 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
    Harbor112070180
    Harbor2180100180
    Harbor3180120180
    Harbor4240140180
    Upland19050190
    Upland2150110190
    Upland3null90190
    Upland4330190190

Signature

WINDOW_AVG(expression, [start, end])