0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

dbtAdvent Calendar 2024

Day 8

dbt のfor文でkey,val をぐるぐるするサンプルと、n回繰り返すサンプル

Last updated at Posted at 2024-12-07
  • 1つのテーブルにkeyとvalが複数あって、それを縦に並べたいときがあるので、組み合わせを定義しといて、あとはunionで繋げるときのサンプル。
{% set dict = 
    {'column_key_1': 'column_val_1', 
     'column_key_2': 'column_val_2'} 
%}

select 
    0 AS column_key,
    'test' AS column_val

{% for key, val in dict.items() %}
    union
    select 
        {{ key }} AS column_key,
        {{ val }} AS column_val,
    from {{ ref('hoge_table') }} 
{% endfor %}

  • n回繰り返すサンプル
    (YYYY-MMを現在の日時から5回遡っていくサンプル)
select TO_CHAR(current_date(),'YYYY-MM') AS yyyymm
{% for i in range(-1,-5,-1) %}
union
select TO_CHAR(DATEADD(MONTH, {{i}} ,current_date()),'YYYY-MM') AS yyyymm
{% endfor %}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?