Skip to content

Commit

Permalink
Update get_query_results_as_dict example to demonstrate accessing col…
Browse files Browse the repository at this point in the history
…umnar results as dictionary values (#474)

* Update get_qu
ery_results_as_dict example to demonstrate accessing columnar results as dictionary values

* Use slugify in example

* Fix slugify example with dbt_utils. package prefix

Co-authored-by: Elize Papineau <elize.papineau@dbtlabs.com>
  • Loading branch information
epapineau and Elize Papineau authored Jan 14, 2022
1 parent 64773b5 commit 1839747
Showing 1 changed file with 18 additions and 10 deletions.
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 -%}
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

0 comments on commit 1839747

Please sign in to comment.