Calculated field
WINDOW_COVARP(SUM([Revenue]), SUM([Cost]))
Compute using: addressing Period; partitioning Region
Sample data
| Region | Period | Revenue | Cost |
|---|---|---|---|
| Harbor | 1 | 120 | 70 |
| Harbor | 2 | 180 | 100 |
| Harbor | 3 | 180 | 120 |
| Harbor | 4 | 240 | 140 |
| Upland | 1 | 90 | 50 |
| Upland | 2 | 150 | 110 |
| Upland | 3 | null | 90 |
| Upland | 4 | 330 | 190 |
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.
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"Written for this dialect; not run here.
SELECT CAST((covar_pop(`Revenue`,`Cost`) OVER (PARTITION BY `Region` ORDER BY `Period` ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) AS FLOAT64) AS result FROM input ORDER BY `Region`, `Period`
Written for this dialect; not run here.
Result
| Region | Period | Revenue | Cost | result |
|---|---|---|---|---|
| Harbor | 1 | 120 | 70 | 1050 |
| Harbor | 2 | 180 | 100 | 1050 |
| Harbor | 3 | 180 | 120 | 1050 |
| Harbor | 4 | 240 | 140 | 1050 |
| Upland | 1 | 90 | 50 | 5733.33 |
| Upland | 2 | 150 | 110 | 5733.33 |
| Upland | 3 | null | 90 | 5733.33 |
| Upland | 4 | 330 | 190 | 5733.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"Region Period Revenue Cost result Harbor 1 120 70 3079.59 Harbor 2 180 100 3079.59 Harbor 3 180 120 3079.59 Harbor 4 240 140 3079.59 Upland 1 90 50 3079.59 Upland 2 150 110 3079.59 Upland 3 null 90 3079.59 Upland 4 330 190 3079.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"Region Period Revenue Cost result Harbor 1 120 70 1050 Harbor 2 180 100 1050 Harbor 3 180 120 1050 Harbor 4 240 140 1050 Upland 1 90 50 5733.33 Upland 2 150 110 5733.33 Upland 3 null 90 5733.33 Upland 4 330 190 5733.33
Signature
WINDOW_COVARP(expression, expression, [start, end])