Skip to content

Instantly share code, notes, and snippets.

@haleemur
Last active February 17, 2021 04:15
Show Gist options
  • Save haleemur/37629d28490957268883e818f64d52c8 to your computer and use it in GitHub Desktop.
Save haleemur/37629d28490957268883e818f64d52c8 to your computer and use it in GitHub Desktop.
using model.columns in dbt
the view definition
```sql
-- target_view.sql
{%- set frame = 'OVER (PARTITION BY transaction_id ORDER BY id DESC)' -%}
SELECT DISTINCT
transaction_id
{%- for f in model['columns'] -%}
{% if f != 'transaction_id' %}
, FIRST_VALUE({{ f }}) {{ frame }} AS {{ f }}
{%- endif -%}
{% endfor %}
, ROUND(DATE_DIFF(
'day'
, FIRST_VALUE(purchase_date) {{ frame }}
, FIRST_VALUE(expires_date) {{ frame }}
) / 30.4) AS purchase_duration_months
FROM {{ ref('src_purchases_table') }}
WHERE deleted_at IS NOT NULL
```
the model definition in the schema.yml file
```yaml
# schema.yml
models:
- name: target_view
columns:
- name: column1
- name: transaction_id
- name: id
- name: user_id
- name: purchase_date
- name: expires_date
```
the compiled output
```sql
-- target/compiled/project/target_view.sql
SELECT DISTINCT
transaction_id
, FIRST_VALUE(column1) OVER (PARTITION BY transaction_id ORDER BY id DESC) column1
, FIRST_VALUE(id) OVER (PARTITION BY transaction_id ORDER BY id DESC) id
, FIRST_VALUE(user_id) OVER (PARTITION BY transaction_id ORDER BY id DESC) user_id
, ROUND(DATE_DIFF(
'day'
, FIRST_VALUE(purchase_date) OVER (PARTITION BY transaction_id ORDER BY id DESC)
, FIRST_VALUE(expires_date) OVER (PARTITION BY transaction_id ORDER BY id DESC)
) / 30.4) AS purchase_duration_months
FROM source.src_purchases_table
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment