Skip to content

Instantly share code, notes, and snippets.

@broepke
Created October 13, 2024 23:55
Show Gist options
  • Save broepke/01c0f3c8fb23bfa1b6a9c63c9f5244ea to your computer and use it in GitHub Desktop.
Save broepke/01c0f3c8fb23bfa1b6a9c63c9f5244ea to your computer and use it in GitHub Desktop.
Dynamic Pivoted Views in SQL using dbt and Jinja
{%- set get_distinct_types -%}
select distinct(ct.content_type_name)
from {{ ref('org_content_types') }} oct
join {{ ref('content_types') }} ct
on oct.content_type_id = ct.content_type_id
{%- endset -%}
{%- set results = run_query(get_distinct_types) -%}
{%- if execute -%}
{%- set content_types = results.columns[0].values() -%}
{%- else -%}
{%- set content_types = [] -%}
{%- endif -%}
with
source as (
select distinct
oct.org_id as org_id,
ct.content_type_name as content_type_name
from {{ ref('org_content_types') }} oct
join {{ ref('content_types') }} ct
on oct.content_type_id = ct.content_type_id
),
final as (
select
org_id,
{%- for content_type in content_types %}
count(case when content_type_name = '{{ content_type }}' then 1 end) as {{ content_type | replace("-", "_") | replace(" ", "_") | replace('&', 'and') | replace('2', 'two') | replace('3', 'three') | replace('4', 'four') | lower }}
{%- if not loop.last -%}, {% endif -%}
{%- endfor %}
from source
group by org_id
)
select *
from final
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment