Calculated field
RUNNING_STDEV(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((stddev_samp("Revenue") OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"Runs the example above.
SELECT CAST((stddev_samp("Revenue") OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"Written for this dialect; not run here.
SELECT CAST((stddev_samp(`Revenue`) OVER (PARTITION BY `Region` ORDER BY `Period` ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)) 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 | 42.4264 |
| Harbor | 3 | 180 | 120 | 34.641 |
| Harbor | 4 | 240 | 140 | 48.9898 |
| Upland | 1 | 90 | 50 | null |
| Upland | 2 | 150 | 110 | 42.4264 |
| Upland | 3 | null | 90 | 42.4264 |
| Upland | 4 | 330 | 190 | 124.9 |
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((stddev_samp("Revenue") OVER ( ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"Region Period Revenue Cost result Harbor 1 120 70 null Harbor 2 180 100 45.8258 Harbor 3 180 120 39.1152 Harbor 4 240 140 52.5357 Upland 1 90 50 21.2132 Upland 2 150 110 38.7298 Upland 3 null 90 39.1152 Upland 4 330 190 80.1784 Matches the calculation
SELECT CAST((stddev_samp("Revenue") OVER (PARTITION BY "Region" ORDER BY "Period" ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)) AS DOUBLE) AS result FROM input ORDER BY "Region", "Period"Region Period Revenue Cost result Harbor 1 120 70 null Harbor 2 180 100 42.4264 Harbor 3 180 120 34.641 Harbor 4 240 140 48.9898 Upland 1 90 50 null Upland 2 150 110 42.4264 Upland 3 null 90 42.4264 Upland 4 330 190 124.9
Signature
RUNNING_STDEV(expression)