12
11

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 5 years have passed since last update.

指定の期間の日付一覧を生成する (Presto)

Last updated at Posted at 2018-04-11

概要

データを生成する際に、データが無くても一覧に出力してほしい要件があったので、
指定の期間の日付一覧を作成する方法を調べた内容をメモしておく。

クエリ(日付一覧)

SELECT
  TD_TIME_FORMAT(n, 'yyyy-MM-dd', 'JST') AS date
FROM (
  SELECT n1
  FROM (
    VALUES
      SEQUENCE(
        TD_TIME_PARSE('2018-01-01', 'JST'), 
        TD_TIME_PARSE('2018-12-31', 'JST'),
        60 * 60 * 24
      )
  ) AS x (n1)
) t1
CROSS JOIN UNNEST(n1) AS t (n)
ORDER BY
  TD_TIME_FORMAT(n, 'yyyy-MM-dd', 'JST') ASC
;

実行結果

date
2018-01-01
  ・
  ・
  ・
2018-12-31

クエリ(月一覧)

@ebyhr さんからアドバイスをもらったクエリに変更

SELECT
  FORMAT_DATETIME(dt, 'Y-MM') AS month
FROM (SELECT 1)
CROSS JOIN UNNEST(
  sequence(
    CAST('2018-01-01' AS date),
    CAST('2018-12-01' AS date),
    INTERVAL '1' MONTH
  )
) AS t(dt)
;

実行結果

2018-01
2018-02
2018-03
2018-04
2018-05
2018-06
2018-07
2018-08
2018-09
2018-10
2018-11
2018-12

終わりの日付を本日と動的にしたい場合は、「CURRENT_DATE」を使ったらいいようです。

SELECT
  FORMAT_DATETIME(dt, 'Y-MM') AS month
FROM (SELECT 1)
CROSS JOIN UNNEST(
  sequence(
    CAST('2018-01-01' AS date),
    CURRENT_DATE,
    INTERVAL '1' MONTH
  )
) AS t(dt)
;

参考サイト

12
11
2

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
12
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?