data-dwh-dbt-project/macros/calculate_aggregation_between_preceeding_x_and_y.sql

30 lines
855 B
MySQL
Raw Normal View History

/*
This macro calculates the aggregation of a metric over a partition of a column,
ordered by another column, with a window of x and y preceeding rows.
It's designed to be placed within a SELECT statement.
If include_all_history is True, then X is ignored.
*/
{% macro calculate_aggregation_between_preceeding_x_and_y(
metric,
aggregation="sum",
partition_by="id_deal",
order_by="date",
x=12,
y=1,
include_all_history=False
) %}
{{ aggregation }} ({{ metric }}) over (
partition by {{ partition_by }}
order by
{{ order_by }} rows between
{% if include_all_history %}
unbounded preceding
{% else %}
{{ x }} preceding
{% endif %}
and {{ y }} preceding
) as {{ aggregation }}_{{ metric }}
{% endmacro %}