'Bigquery macros/repeated query parts
We use Bigquery to calculate a many of our daily metrics, but we are always interested in longer term averages (7day, 14day, 28day, QTD, YTD) as well.
This is always done like this (ds: date):
AVG(metric_1d) OVER (
ORDER BY ds
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS metric_7d,
AVG(metric_1d) OVER (
ORDER BY ds
ROWS BETWEEN 13 PRECEDING AND CURRENT ROW
) AS metric_14d,
AVG(metric_1d) OVER (
ORDER BY ds
ROWS BETWEEN 27 PRECEDING AND CURRENT ROW
) AS metric_28d,
AVG(metric_1d) OVER (
PARTITION BY CONCAT(EXTRACT(YEAR FROM ds), DIV(EXTRACT(MONTH FROM ds)-1, 3))
ORDER BY ds
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS metric_qtd,
AVG(metric_1d) OVER (
PARTITION BY EXTRACT(YEAR FROM ds)
ORDER BY ds
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS metric_ytd,
ds
FROM (
SELECT
... AS metric_1d
...
What I do not like is that basically the same code is repeated in all metrics queries (sometimes multiple times if there are multiple metrics calculated). Is there a recommended way to simplify this, maybe using some sort of macro or UDF?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
