Calculated field
WINDOW_VAR(SUM([Revenue]))
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((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.
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"Written for this dialect; not run here.
SELECT CAST((var_samp(`Revenue`) 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 | 2400 |
| Harbor | 2 | 180 | 100 | 2400 |
| Harbor | 3 | 180 | 120 | 2400 |
| Harbor | 4 | 240 | 140 | 2400 |
| Upland | 1 | 90 | 50 | 15600 |
| Upland | 2 | 150 | 110 | 15600 |
| Upland | 3 | null | 90 | 15600 |
| Upland | 4 | 330 | 190 | 15600 |
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"Region Period Revenue Cost result Harbor 1 120 70 6428.57 Harbor 2 180 100 6428.57 Harbor 3 180 120 6428.57 Harbor 4 240 140 6428.57 Upland 1 90 50 6428.57 Upland 2 150 110 6428.57 Upland 3 null 90 6428.57 Upland 4 330 190 6428.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"Region Period Revenue Cost result Harbor 1 120 70 2400 Harbor 2 180 100 2400 Harbor 3 180 120 2400 Harbor 4 240 140 2400 Upland 1 90 50 15600 Upland 2 150 110 15600 Upland 3 null 90 15600 Upland 4 330 190 15600
Signature
WINDOW_VAR(expression, [start, end])