I need to calculate few metrics for a period of days. The requirement is - For a given day, calculate the metrics based on the past 7 days. I need to output the metrics for every day for the past 2 months.
I am trying to implement a nested loop, where I am trying to calculate all days for the last 2 months, and for each day in that loop, I am trying to calculate the sum of recs loaded for the past 7 days (from that day).
I wrote the following query, but CAN'T get it to work as it is going into an infinite loop.
Can anyone please help me fix the query below ?
WITH -- not working !!!
RECURSIVE gen_dates AS (
SELECT
DATE'2025-05-27' AS days
UNION ALL
SELECT
days - 1
FROM
gen_dates
WHERE
days >= days - 60),
iter_days AS (
SELECT days AS iter
FROM gen_dates
UNION ALL
SELECT iter - 1
FROM iter_days
WHERE iter >= iter - 7
),
get_dates AS (
SELECT
a.tgt_tbl,
DATE(a.job_dtm) AS job_dtm,
a.num_recs
FROM
`my_project.my_dataset.audit_tbl` a
JOIN
iter_days b
ON
DATE(a.job_dtm) = b.iter
AND a.tgt_tbl = 'CUSTOMER_SALES'
),
calc_sum AS (
SELECT
tgt_tbl,
job_dtm,
num_recs,
SUM(num_recs) OVER (PARTITION BY tgt_tbl ORDER BY DATE(job_dtm) DESC ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING) AS sum_cnt
FROM
get_dates
)
SELECT
tgt_tbl,
job_dtm,
FORMAT_DATE('%a', job_dtm) AS dayofweek,
num_recs,
sum_cnt,
ROUND(sum_cnt/6) AS avg_cnt,
ROUND(((ROUND(sum_cnt/6) - num_recs) / ROUND(sum_cnt/6)) * 100, 2) AS pct
FROM calc_sum
ORDER BY 2 DESC;
Thanks.
job_ctrl_tbl
to itself on the ids andb.job_run_dtm Between Date_Add(a.job_run_dtm,Interval -6 DAY) And a.job_run_dtm
Then you can just sum up the table b valuesformat_date(%a, <date)
to get the short name for a day, no need to hard code it like you have.