LoginSignup
10
6

More than 3 years have passed since last update.

Metabase 日付型の変数のデフォルトを相対的にする

Last updated at Posted at 2020-05-13

metabaseのクエリには{{変数名}}と記載することで変数を利用して任意の値を入力し、データを表示することができる。
この機能は変数ではデフォルトの値を設定することができる。

しかしデフォルトの機能では変数の日付型は、固定の日付しか設定することができず、直近1週間 というような範囲指定ができない。
これをSQLを工夫することで解決する方法を提示する。

前提条件

MetabaseのデータソースのDBMSはPostgreSQLを利用

デフォル期間を表すSQL

coalesceとcurrent_dateを利用して、変数が設定されていない場合にはcurrent_dateを利用する

対象の箇所を抜き出したSQL

s.created_at 
  BETWEEN 
    coalesce([[{{from_date}},]] current_date - '1 week'::interval)
  and
    coalesce([[{{to_date}},]] current_date) 

上記を利用した日付ごとにまとめたSQL例

select 
    sum(user_id) ,
    date_trunc('day', created_at) as day
from
  a_table
where 
    created_at BETWEEN coalesce([[{{from_date}},]] current_date - '1 week'::interval) and coalesce([[{{to_date}},]] current_date) 
group by date_trunc('day', created_at)
order by date_trunc('day', created_at)

ref: https://www.wantedly.com/projects/432393?fbclid=IwAR1_jZ0-xxi2jSl3CIlA-j9PDLZOz-msEGEWc5ekeMxPQB38fIbw5fsyBD4

10
6
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
10
6