WINDOW_CORR: from Tableau to SQL

Calculates the regional paired revenue and cost statistic using non-null pairs. Below, 8 sample rows go through the calculation and through the SQL, and both return the same numbers.

Calculated field

WINDOW_CORR(SUM([Revenue]), SUM([Cost]))

Compute using: addressing Period; partitioning Region

Sample data

RegionPeriodRevenueCost
Harbor112070
Harbor2180100
Harbor3180120
Harbor4240140
Upland19050
Upland2150110
Upland3null90
Upland4330190

The same calculation as SQL

SELECT CAST((corr("Revenue","Cost") 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
Harbor1120700.95702
Harbor21801000.95702
Harbor31801200.95702
Harbor42401400.95702
Upland190500.980316
Upland21501100.980316
Upland3null900.980316
Upland43301900.980316

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((corr("Revenue","Cost") OVER ( ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"
    RegionPeriodRevenueCostresult
    Harbor1120700.974543
    Harbor21801000.974543
    Harbor31801200.974543
    Harbor42401400.974543
    Upland190500.974543
    Upland21501100.974543
    Upland3null900.974543
    Upland43301900.974543

    Matches the calculation

    SELECT CAST((corr("Revenue","Cost") 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
    Harbor1120700.95702
    Harbor21801000.95702
    Harbor31801200.95702
    Harbor42401400.95702
    Upland190500.980316
    Upland21501100.980316
    Upland3null900.980316
    Upland43301900.980316

Signature

WINDOW_CORR(expression, expression, [start, end])