Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

概要

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

クエリ(日付一覧)

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)
;

参考サイト

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした