0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【データ基盤構築/dbt】WHERE句に前日分データを差分追加するための述語を記述する

Last updated at Posted at 2023-02-24

今回の課題

前日分のデータをテーブルに増分更新で追加するためのクエリを作成したかったのだが、

Compilation Error in model [モデル名]

というエラーが発生してつまずいてしまった。

エラーが発生したコード

select
    *
from
    `ソーステーブル名`
{% if is_incremental() %}
where
    {%- set target_date = var('target_date', '') %}
    {%- if target_date != '' %}
    {{ dbt.date_trunc('day', 'date') }} = {{ dbt.date_trunc('day', "'"~target_date~"'") }}
    {%- else %}
    {{ dbt.date_trunc('day', 'date') }} = {{ dbt.date_trunc('day', date_sub(dbt.current_timestamp(), interval 1 day)) }}
    {%- endif %}
{% endif %}   

エラーが発生した原因は、
{{}}の中に、date_sub関数を記述してしまっていたことだった。

エラーを解決したクエリ

select
    *
from
    `ソーステーブル名`
{% if is_incremental() %}
where
    {%- set target_date = var('target_date', '') %}
    {%- if target_date != '' %}
    {{ dbt.date_trunc('day', 'date') }} = {{ dbt.date_trunc('day', "'"~target_date~"'") }}
    {%- else %}
    {{ dbt.date_trunc('day', 'date') }} = date_sub({{ dbt.date_trunc('day', dbt.current_timestamp()) }}, interval 1 day)
    {%- endif %}
{% endif %}   

このように、{{}}の外側にdate_sub()関数を使用することで、前日分データをテーブルに追加するクエリを作成することができた。

おまけ:{{}}について調べてみた。

{{ ... }}・・・式。式の結果を文字列として出力する。
{% ... %}・・・制御構文。 for や if などのように処理の流れを制御する。
{# ... #}・・・コメント。 人がプログラムを読みやすくなるようにコメントを機医術可能。最終的なSQLに出力されない。

※参考:Jinjaの基礎

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?