WINDOW_VAR: from Tableau to SQL

Calculates var 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_VAR(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((var_samp("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
Harbor1120702400
Harbor21801002400
Harbor31801202400
Harbor42401402400
Upland1905015600
Upland215011015600
Upland3null9015600
Upland433019015600

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((var_samp("Revenue") OVER ( ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"
    RegionPeriodRevenueCostresult
    Harbor1120706428.57
    Harbor21801006428.57
    Harbor31801206428.57
    Harbor42401406428.57
    Upland190506428.57
    Upland21501106428.57
    Upland3null906428.57
    Upland43301906428.57

    Matches the calculation

    SELECT CAST((var_samp("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
    Harbor1120702400
    Harbor21801002400
    Harbor31801202400
    Harbor42401402400
    Upland1905015600
    Upland215011015600
    Upland3null9015600
    Upland433019015600

Signature

WINDOW_VAR(expression, [start, end])