-
Notifications
You must be signed in to change notification settings - Fork 504
/
recency.sql
41 lines (27 loc) · 1.13 KB
/
recency.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
{% test recency(model, field, datepart, interval, ignore_time_component=False, group_by_columns = []) %}
{{ return(adapter.dispatch('test_recency', 'dbt_utils')(model, field, datepart, interval, ignore_time_component, group_by_columns)) }}
{% endtest %}
{% macro default__test_recency(model, field, datepart, interval, ignore_time_component, group_by_columns) %}
{% set threshold = 'cast(' ~ dbt.dateadd(datepart, interval * -1, dbt.current_timestamp()) ~ ' as ' ~ ('date' if ignore_time_component else dbt.type_timestamp()) ~ ')' %}
{% if group_by_columns|length() > 0 %}
{% set select_gb_cols = group_by_columns|join(' ,') + ', ' %}
{% set groupby_gb_cols = 'group by ' + group_by_columns|join(',') %}
{% endif %}
with recency as (
select
{{ select_gb_cols }}
{% if ignore_time_component %}
cast(max({{ field }}) as date) as most_recent
{%- else %}
max({{ field }}) as most_recent
{%- endif %}
from {{ model }}
{{ groupby_gb_cols }}
)
select
{{ select_gb_cols }}
most_recent,
{{ threshold }} as threshold
from recency
where most_recent < {{ threshold }}
{% endmacro %}