[英]Get column names AND types using star macro in dbt
使用星形宏,除了列名之外,還有沒有辦法獲取列數據類型(布爾值、數字等)?
例如,此查詢使用星形宏從引用表中收集列名,將其保存為數組變量column_names
,然后循環遍歷該數組並將 max 函數應用於所有列。
{% set column_names = star(
from=ref_table,
except=["a", "b", "c"],
as_list=True)
%}
select
date_trunc('week', day) as week,
name,
{%- for col in column_names %}
max({{ col|lower }}) as {{ col | lower }}{%- if not loop.last %},{{ '\n ' }}{% endif %}
{%- endfor %}
from {{ ref('my_table_name') }}
group by 1, 2
我想有條件地將 max 函數僅應用於布爾列。
這可能看起來像
{%- for col in column_names %}
{% if is_boolean(col) %}
max({{ col|lower }}) as {{ col | lower }}{%- if not loop.last %},{{ '\n ' }}{% endif %}
{% endif %}
{%- endfor %}
但問題是星宏將列名作為字符串傳遞,因此它不攜帶任何元數據。
我如何在這里獲取列數據類型?
數據倉庫:雪花
您可以在此處查看dbt_utils.star
的源代碼
在后台,它使用dbt_utils.get_filtered_columns_in_relation
。 該宏也只返回列名。 然而! 該宏使用內置的adapter.get_columns_in_relation
,它返回具有dtype
屬性的Column對象列表。
所以你的代碼變成:
{% set all_columns = adapter.get_columns_in_relation(
ref("my_table")
) %}
{% set except_col_names=["a", "b", "c"] %}
select
date_trunc('week', day) as week,
name,
{%- for col in all_columns if col.name not in except_col_names %}
{% if col.data_type == 'BOOLEAN' %}
max({{ col.name|lower }}) as {{ col.name|lower }}{%- if not loop.last %},{{ '\n ' }}{% endif %}
{% endif %}
{%- endfor %}
from {{ ref('my_table_name') }}
group by 1, 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.