在其他宏中声明其他宏中的var
主要想法是具有恒定变量,然后有可能在代码或宏的其他部分中使用它作为DBT。
包含常数的宏的示例:
{% macro constant_vars() -%}
{%
set var_1 = {
"0": ["0"],
"1": ["1", "11", "111"]
}
%}
{%
set var_2 = {
"2": ["2"],
"3": ["3"]
}
%}
{%- endmacro -%}
使用以前的宏:
{% macro evaluate(
column_to_check
) -%}
CASE
{% for map_key in var_1 -%}
WHEN ({{column_to_check}} IN UNNEST( {{ var_1[map_key] }})) THEN
'{{ map_key }}'
{% endfor -%}
ELSE
"-1"
END
{%- endmacro -%}
为dbt创建的sql句子中的常数:
SELECT
[..]
evaluate(column1)
[..]
FROM
table
dbt编译的查询:
SELECT
[..]
CASE
WHEN (column1 IN UNNEST(["0"])) THEN
'0'
WHEN (column1 IN UNNEST(["1", "11", "111"])) THEN
'1'
ELSE
"-1"
END
[..]
FROM
table
是否有可能?存在另一种做到这一点的方式?
谢谢!
The main idea is to have a constant variable and then have the possibility to use it in other parts of the code or macros for DBT.
Example of a macro that contains constants:
{% macro constant_vars() -%}
{%
set var_1 = {
"0": ["0"],
"1": ["1", "11", "111"]
}
%}
{%
set var_2 = {
"2": ["2"],
"3": ["3"]
}
%}
{%- endmacro -%}
Macro that use a constant from the previous macro:
{% macro evaluate(
column_to_check
) -%}
CASE
{% for map_key in var_1 -%}
WHEN ({{column_to_check}} IN UNNEST( {{ var_1[map_key] }})) THEN
'{{ map_key }}'
{% endfor -%}
ELSE
"-1"
END
{%- endmacro -%}
SQL sentence created for DBT:
SELECT
[..]
evaluate(column1)
[..]
FROM
table
DBT compiled query:
SELECT
[..]
CASE
WHEN (column1 IN UNNEST(["0"])) THEN
'0'
WHEN (column1 IN UNNEST(["1", "11", "111"])) THEN
'1'
ELSE
"-1"
END
[..]
FROM
table
Is it possible? Exist another way to do that?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使用
{%设置my_var = ...%}
在范围中声明的变量,这意味着在您设置的位置之外不会在任何情况下声明它们。DBT还支持
var
宏,可以充当全局变量。”您的
dbt_project.yml
这样的文件:然后使用
{{var('var_1')}}}
访问值。另一个选择是返回来自宏的变量。如果值不是静态/文字,则可以很好地工作:
然后您可以调用宏并将其分配给模型中的变量:
Variables you declare using
{% set my_var = ... %}
are local in scope, meaning that they won't be declared in any contexts outside of where you set them.dbt also supports a
var
macro, which can act as global variables. Docs for varYou set
var
in yourdbt_project.yml
file like this:and then access the values using
{{ var('var_1') }}
.Another option is to return the variable(s) from the macro. This would work well if the values are not static/literals:
Then you can call the macro and assign it to a variable in your model: