-
Notifications
You must be signed in to change notification settings - Fork 100
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Check for period over period changes in column sum
- Loading branch information
1 parent
0c61978
commit d616254
Showing
2 changed files
with
91 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
{% macro period_over_period_change(columns, period_column, threshold, dimensions, date_where, field_where) %} | ||
{% if columns is string %} | ||
{% set columns = [columns] %} | ||
{% endif %} | ||
{% if dimensions is string %} | ||
{% set dimensions = [dimensions] %} | ||
{% endif %} | ||
WITH cte AS ( | ||
SELECT | ||
{{ period_column }}, | ||
{% for dim in dimensions %} | ||
{{ dim }}, | ||
{% endfor %} | ||
{% for col in columns %} | ||
SUM(COALESCE({{ col }}, 0)) AS {{ col }}, | ||
{% endfor %} | ||
FROM | ||
`{{ project_id }}.{{ dataset_id }}.{{ table_name }}` | ||
{% if field_where %} | ||
WHERE {{ field_where }} | ||
{% endif %} | ||
GROUP BY | ||
{% for dim in dimensions %} | ||
{{ dim }}, | ||
{% endfor %} | ||
{{ period_column }} | ||
), | ||
changes AS ( | ||
SELECT [ | ||
{% for col in columns %} | ||
IF( | ||
COUNTIF( | ||
SAFE_DIVIDE( | ||
{{ col }}, | ||
LAG({{ col }}) | ||
OVER( | ||
{% if dimensions %} | ||
PARTITION BY | ||
{% for dim in dimensions %} | ||
{{ dim }} | ||
{{ ", " if not loop.last else "" }} | ||
{% endfor %} | ||
{% endif %} | ||
ORDER BY {{ period_column }} ASC | ||
) | ||
) > {{ threshold }} | ||
) > 0, | ||
"{{ col }}", | ||
NULL | ||
){% if not loop.last -%},{% endif -%} | ||
{% endfor %} | ||
] AS checks | ||
FROM cte | ||
WHERE {{ date_where }} | ||
), | ||
change_checks AS ( | ||
SELECT ARRAY_AGG(u IGNORE NULLS) AS checks FROM changes, UNNEST(checks) AS u | ||
) | ||
SELECT IF( | ||
(SELECT ARRAY_LENGTH(checks) FROM change_checks) > 0, | ||
ERROR( | ||
CONCAT( | ||
"Columns with period over period changes over {{ threshold }}: ", | ||
(SELECT ARRAY_TO_STRING(checks, ", ") FROM range_checks) | ||
) | ||
), | ||
NULL | ||
); | ||
{% endmacro %} |
d616254
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Integration report for "Check for period over period changes in column sum"
sql.diff
Click to expand!