I\'m trying to compute a 28 day moving sum in BigQuery using the LAG function.
The top answer to this question
Bigquery SQL for sliding window aggregate
Here is an alternate take that I found to be flexible and effective:
WITH users AS
(SELECT 'Isabella' as user, 1 as spend, DATE(2020, 03, 28) as date
UNION ALL SELECT 'Isabella', 2, DATE(2020, 03, 29)
UNION ALL SELECT 'Daniel', 3, DATE(2020, 03, 24)
UNION ALL SELECT 'Andrew', 4, DATE(2020, 03, 23)
UNION ALL SELECT 'Daniel', 5, DATE(2020, 03, 11)
UNION ALL SELECT 'Jose', 6, DATE(2020, 03, 17))
SELECT
user,
max(sum(case date_diff(date(2020,04,15), date, day) between 0 and 28
when true then spend else 0 end)) over(partition by user) as spend_28_day_sum
FROM users
group by user
+------------------------------+
| user | spend_28_day_sum |
+------------------------------+
| Andrew | 4 |
| Daniel | 3 |
| Isabella | 3 |
| Jose | 0 |
+------------------------------+
You could change the specified date for the "window function" to current_date() or cross join with a generated date array to see how users change over time.