Calculated field
WINDOW_AVG(SUM([Revenue]), -1, 1)
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((avg("Revenue") OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"Runs the example above.
SELECT CAST((avg("Revenue") OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"Written for this dialect; not run here.
SELECT CAST((avg(`Revenue`) OVER (PARTITION BY `Region` ORDER BY `Period` ROWS BETWEEN 1 PRECEDING AND 1 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 | 150 |
| Harbor | 2 | 180 | 100 | 160 |
| Harbor | 3 | 180 | 120 | 200 |
| Harbor | 4 | 240 | 140 | 210 |
| Upland | 1 | 90 | 50 | 120 |
| Upland | 2 | 150 | 110 | 120 |
| Upland | 3 | null | 90 | 240 |
| Upland | 4 | 330 | 190 | 330 |
Same rows from the calculation and from the SQL in DuckDB.
Where a naive translation goes wrong
- An unpartitioned SQL window mixes independent regional calculation sequences.
Naive SQL
SELECT CAST((avg("Revenue") OVER ( ORDER BY "Period" ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"Region Period Revenue Cost result Harbor 1 120 70 105 Harbor 2 180 100 140 Harbor 3 180 120 165 Harbor 4 240 140 285 Upland 1 90 50 130 Upland 2 150 110 170 Upland 3 null 90 210 Upland 4 330 190 285 Matches the calculation
SELECT CAST((avg("Revenue") OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"Region Period Revenue Cost result Harbor 1 120 70 150 Harbor 2 180 100 160 Harbor 3 180 120 200 Harbor 4 240 140 210 Upland 1 90 50 120 Upland 2 150 110 120 Upland 3 null 90 240 Upland 4 330 190 330
Signature
WINDOW_AVG(SUM([Revenue]), -1, 1)