dbt jinja 返回查询结果
dbt jinja returning the results of a query
我正在尝试模拟以下情况:
给定一些查询,return 多列结果集(例如
run_query
或db_utils.get_query_results_as_dict
在 case/statment
中迭代
例如:
{% set conditions = dbt_utils.get_query_results_as_dict("select comment, criteria from "
~ ref('the_model') %}
...
select case
{% for condition in conditions %}
when {{ condition["criteria"] }}
then {{ condition["comment"] }}
{% endfor %}
无法使它正常工作,感谢任何指导。
我尝试过的一些想法:
- get_column_values x2 并将它们压缩到一个新的元组列表中。
zip not recognised
- 从
the_model
获取计数 (*),然后尝试遍历 运行ge - 运行 到类型问题 - 各种
for
条件{% for k, v in conditions.items() %}
能够通过以下方式自行解决:
{% set conditions = dbt_utils.get_query_results_as_dict("select criteria, comment from " ~ ref('reference_data') ~ " order by sequence desc") %}
with main as (
select * from {{ ref('my_other_model') }}
),
-- [NEEDS_REVIEW] there's probably a cleaner way to do this iteration - however it's interpolated result. Could do with the zip function.
comments as (
select
*,
case
{# {{- log(conditions, info=True) -}} #}
{%- for comment in conditions.COMMENT -%}
when {{ conditions.CRITERIA[loop.index0] }}
then '{{ comment }}'
{% endfor %}
end as comment
from main
)
select * from comments
陷阱:
- 这是在雪花上,所以函数返回的键将是 up-cased,因为这是我加载数据的方式。
- 使用
loop.index0
获取循环的当前迭代并索引到另一个元组集合(在本例中为CRITERIA
)。 - 我在我的参考数据中添加了一个
SEQUENCE
键,只是为了通过使用它来订购来确保一致的渲染。标准确实重叠 a-little 位,所以这很重要。