WINDOW_COVARP: 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_COVARP(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((covar_pop("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
Harbor1120701050
Harbor21801001050
Harbor31801201050
Harbor42401401050
Upland190505733.33
Upland21501105733.33
Upland3null905733.33
Upland43301905733.33

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((covar_pop("Revenue","Cost") OVER ( ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"
    RegionPeriodRevenueCostresult
    Harbor1120703079.59
    Harbor21801003079.59
    Harbor31801203079.59
    Harbor42401403079.59
    Upland190503079.59
    Upland21501103079.59
    Upland3null903079.59
    Upland43301903079.59

    Matches the calculation

    SELECT CAST((covar_pop("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
    Harbor1120701050
    Harbor21801001050
    Harbor31801201050
    Harbor42401401050
    Upland190505733.33
    Upland21501105733.33
    Upland3null905733.33
    Upland43301905733.33

Signature

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