0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SQLである期間内の日付を全て列挙する

Posted at

動機としては、ある期間内の日付を全て列挙し、日付でGROUP BYした調査対象のtableにOUTER JOINをかけることで、ある日付が集計結果で抜けることなくちゃんと0件であることを出そうとしていて見つけました。

1. 再帰 CTE

RECURSIVEって正直使ったことなかったんですが、便利ですね。

WITH RECURSIVE date_series AS (
  SELECT DATE('2025-01-01') AS date_  -- 開始日
  UNION ALL
  SELECT DATE_ADD(date_, INTERVAL 1 DAY)
  FROM date_series
  WHERE date_ < DATE('2025-01-31') -- 終了日
)
SELECT date_ FROM date_series
ORDER BY date_;

Reference

2. GENERATE_DATE_ARRAY()

うーん、まあ関数が用意されているならこちらでいいかな…

SELECT GENERATE_DATE_ARRAY('2025-01-01', '2025-01-31') AS example;

Reference

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?