{% macro revenue_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 }},
      COALESCE(LOGICAL_OR({{ date_where }})) AS date_check,
      {% 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(
          SAFE_DIVIDE(
            ABS({{ 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
              )),
            ABS(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 }},
          "{{ col }}",
          NULL
        ){% if not loop.last -%},{% endif -%}
      {% endfor %}
    ] AS checks,
    date_check
    FROM cte
    ORDER BY {{ period_column }} DESC
  ),
  change_checks AS (
    SELECT ARRAY_AGG(u IGNORE NULLS) AS checks FROM changes, UNNEST(checks) AS u WHERE date_check
  )
  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 change_checks)
     )
   ),
   NULL
  );
{% endmacro %}
