Calculated field
(SUM([Revenue]) - LOOKUP(SUM([Revenue]), -1)) / ABS(LOOKUP(SUM([Revenue]), -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((("Revenue" - lag("Revenue",1) OVER (PARTITION BY "Region" ORDER BY "Period")) / nullif(abs(lag("Revenue",1) OVER (PARTITION BY "Region" ORDER BY "Period")),0)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"Runs the example above.
SELECT CAST((("Revenue" - lag("Revenue",1) OVER (PARTITION BY "Region" ORDER BY "Period")) / nullif(abs(lag("Revenue",1) OVER (PARTITION BY "Region" ORDER BY "Period")),0)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"Written for this dialect; not run here.
SELECT CAST(((`Revenue` - lag(`Revenue`,1) OVER (PARTITION BY `Region` ORDER BY `Period`)) / nullif(abs(lag(`Revenue`,1) OVER (PARTITION BY `Region` ORDER BY `Period`)),0)) 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 | null |
| Harbor | 2 | 180 | 100 | 0.5 |
| Harbor | 3 | 180 | 120 | 0 |
| Harbor | 4 | 240 | 140 | 0.333333 |
| Upland | 1 | 90 | 50 | null |
| Upland | 2 | 150 | 110 | 0.666667 |
| Upland | 3 | null | 90 | null |
| Upland | 4 | 330 | 190 | null |
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((("Revenue" - lag("Revenue",1) OVER ( ORDER BY "Period")) / nullif(abs(lag("Revenue",1) OVER ( ORDER BY "Period")),0)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"Region Period Revenue Cost result Harbor 1 120 70 null Harbor 2 180 100 1 Harbor 3 180 120 0.2 Harbor 4 240 140 null Upland 1 90 50 -0.25 Upland 2 150 110 -0.166667 Upland 3 null 90 null Upland 4 330 190 0.375 Matches the calculation
SELECT CAST((("Revenue" - lag("Revenue",1) OVER (PARTITION BY "Region" ORDER BY "Period")) / nullif(abs(lag("Revenue",1) OVER (PARTITION BY "Region" ORDER BY "Period")),0)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"Region Period Revenue Cost result Harbor 1 120 70 null Harbor 2 180 100 0.5 Harbor 3 180 120 0 Harbor 4 240 140 0.333333 Upland 1 90 50 null Upland 2 150 110 0.666667 Upland 3 null 90 null Upland 4 330 190 null
Signature
(SUM([Revenue]) - LOOKUP(SUM([Revenue]), -1)) / ABS(LOOKUP(SUM([Revenue]), -1))