diff --git a/macros/dbt_expectations/schema_tests/distributional/expect_column_values_to_be_within_n_moving_stdevs.sql b/macros/dbt_expectations/schema_tests/distributional/expect_column_values_to_be_within_n_moving_stdevs.sql index 5342e83..52afe2f 100644 --- a/macros/dbt_expectations/schema_tests/distributional/expect_column_values_to_be_within_n_moving_stdevs.sql +++ b/macros/dbt_expectations/schema_tests/distributional/expect_column_values_to_be_within_n_moving_stdevs.sql @@ -13,6 +13,7 @@ coalesce({{ metric_column }}, 0) {% macro sqlserver__test_expect_column_values_to_be_within_n_moving_stdevs(model, column_name, date_column_name, + group_by, period, lookback_periods, trend_periods, @@ -26,18 +27,24 @@ coalesce({{ metric_column }}, 0) {%- set sigma_threshold_upper = sigma_threshold_upper if sigma_threshold_upper else sigma_threshold -%} {%- set sigma_threshold_lower = sigma_threshold_lower if sigma_threshold_lower else -1 * sigma_threshold -%} +{%- set partition_by = "partition by " ~ (group_by | join(",")) if group_by -%} +{%- set group_by_length = (group_by | length ) if group_by else 0 -%} - +{# TODO: adapt to new group_by arg #} with grouped_metric_values as ( select {{ dbt_utils.date_trunc(period, date_column_name) }} as metric_period, + {{ group_by | join(",") ~ "," if group_by }} sum({{ column_name }}) as agg_metric_value from {{ model }} group by {{ dbt_utils.date_trunc(period, date_column_name) }} + {% if group_by %} + , {{ group_by | join(",") }} + {% endif %} ), @@ -45,7 +52,7 @@ grouped_metric_values_with_priors as ( select *, - lag(agg_metric_value, {{ lookback_periods }}) over(order by metric_period) as prior_agg_metric_value + lag(agg_metric_value, {{ lookback_periods }}) over({{ partition_by }} order by metric_period) as prior_agg_metric_value from grouped_metric_values d @@ -81,10 +88,10 @@ metric_moving_calcs as ( select *, avg(metric_test_value) - over(order by metric_period rows + over({{ partition_by }} order by metric_period rows between {{ trend_periods }} preceding and 1 preceding) as metric_test_rolling_average, stdev(metric_test_value) - over(order by metric_period rows + over({{ partition_by }} order by metric_period rows between {{ trend_periods }} preceding and 1 preceding) as metric_test_rolling_stddev from metric_values @@ -101,7 +108,7 @@ metric_sigma as ( ) select - count(*) + count(*) as count from metric_sigma where