14
12

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.

カレンダーテーブルの代替

Last updated at Posted at 2013-01-23

MySQLで自然数の連番を持つ集合を作成

↑こちらの記事を読んで、日時で同じことができそうと思って書いたのがこれ↓

-- 2010/02/01~2010/02/28を取得
 SELECT
   @f:='2010-02-01'
 UNION ALL
 SELECT
   @f:=DATE_ADD(@f, INTERVAL 1 DAY)
 FROM
   SomeTable    -- 取得したい行数以上のレコードがあるテーブル
 WHERE
   @f < '2010-02-28'

これをFROM句に入れると、日別集計などをするときに便利。

あまり長期間だとSomeTableを用意するほうが大変かもだけど…

追記(2017/03/29)

なんだかんだで何年も便利に使っているので、DB2版の例も。

with CAL(TS) as ( 
  select timestamp(date('2015-09-01'), time('00:00:00')) TS from SYSIBM.SYSDUMMY1
  union all 
  select TS + 1 day from CAL where TS + 1 day < timestamp(date('2015-10-01'), time('00:00:00'))
) 
select year(CAL.TS)*10000 + month(CAL.TS)*100 + day(CAL.TS) YMD from CAL
14
12
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
14
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?