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?

More than 5 years have passed since last update.

SQLの小ワザ(指定した日付から、指定した日数分の日付を取得する)

Posted at

はじめに

ほぼタイトルで完結していますが、「指定した日付から、指定した日数分の日付を取得するSQL」をご紹介します。
やってる事は何てことない & あんまり使いどころないですが、何かの足しになればと。
※ MySQL5.6の環境で実行しています。

コード

下記のような感じです。
この例では、 2017-01-01 から、1000日分の日付を取得しています。

select
  date_format(date_add('2016-12-31', interval numbers.generate_series day), '%Y-%m-%d') as date
from
(
  SELECT 0 generate_series FROM DUAL WHERE (@num:=1-1)*0 UNION ALL
  SELECT @num:=@num+1 FROM `information_schema`.COLUMNS LIMIT 1000
) as numbers
;

結果

"2017-01-01"
"2017-01-02"
"2017-01-03"
"2017-01-04"
"2017-01-05"
"2017-01-06"
"2017-01-07"
"2017-01-08"
"2017-01-09"
"2017-01-10"
"2017-01-11"
"2017-01-12"
"2017-01-13"
"2017-01-14"
.
.

ちょっと解説

下記の部分で、1〜1000までの数字を取得しています。

  SELECT 0 generate_series FROM DUAL WHERE (@num:=1-1)*0 UNION ALL
  SELECT @num:=@num+1 FROM `information_schema`.COLUMNS LIMIT 1000

それを、 date_add で日付に加算しているだけです。

最後に

分かってしまえばなんて事はないコードですが、SQLにあまり触れてないエンジニアの方だと、ぱっと見意味不明だと思います。
正直、あんまり使うケースはない気もします。マスタデータ作成したり、データマート作る時に使ったりくらいですかね・・・。
SQL楽しいです。

0
0
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
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?