Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update get_query_results_as_dict example to demonstrate accessing columnar results as dictionary values #474

Merged
merged 3 commits into from
Jan 14, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 18 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -658,17 +658,25 @@ This macro returns a dictionary from a sql query, so that you don't need to inte

**Usage:**
```
-- Returns a dictionary of the users table where the state is California
{% set california_cities = dbt_utils.get_query_results_as_dict("select * from" ~ ref('cities') ~ "where state = 'CA' and city is not null ") %}
{% set sql_statement %}
select city, state from {{ ref('users) }}
{% endset %}

{%- set places = dbt_utils.get_query_results_as_dict(sql_statement) -%}

select
city,
{% for city in california_cities %}
sum(case when city = {{ city }} then 1 else 0 end) as users_in_{{ city }},
{% endfor %}
count(*) as total
from {{ ref('users') }}

group by 1
{% for city in places['CITY'] | unique -%}
epapineau marked this conversation as resolved.
Show resolved Hide resolved
sum(case when city = '{{ city }}' then 1 else 0 end) as users_in_{{ dbt_utils.slugify(city) }},
{% endfor %}

{% for state in places['STATE'] | unique -%}
sum(case when state = '{{ state }}' then 1 else 0 end) as users_in_{{ state }},
{% endfor %}

count(*) as total_total

from {{ ref('users') }}
```

### SQL generators
Expand Down Expand Up @@ -1043,7 +1051,7 @@ select
order_id,
{%- for payment_method in payment_methods %}
sum(case when payment_method = '{{ payment_method }}' then amount end)
as {{ slugify(payment_method) }}_amount,
as {{ dbt_utils.slugify(payment_method) }}_amount,

{% endfor %}
...
Expand Down