【问题标题】:dbt jinja returning the results of a querydbt jinja 返回查询结果
【发布时间】:2020-08-07 09:08:52
【问题描述】:

我正在尝试模拟以下情况:

  • 给定一些查询,返回多列结果集(例如 run_querydb_utils.get_query_results_as_dict

  • 在一个案例/陈述中迭代

例如:

{% 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 获取计数 (*),然后尝试迭代范围 - 遇到类型问题
  • 各种for条件{% for k, v in conditions.items() %}

【问题讨论】:

  • 您在共享示例中看到的 for 循环条件有什么错误?

标签: jinja2 dbt


【解决方案1】:

能够通过以下方式自行解决:

{% 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

问题:

  • 这是在雪花上,所以函数返回的键将被大写,因为这就是我加载数据的方式。
  • 使用loop.index0 获取循环的当前迭代并索引到其他元组集合(在本例中为CRITERIA)。
  • 我在我的参考数据中添加了一个SEQUENCE 键,只是为了通过使用它来确保一致的渲染。标准确实有点重叠,所以这很重要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    • 1970-01-01
    相关资源
    最近更新 更多