Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
8
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

@reflet

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

概要

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

クエリ(日付一覧)

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
8
Help us understand the problem. What are the problem?