SQL语句生成时间维度表

转载地址:
https://blog.csdn.net/neweastsun/article/details/43866599

感谢大佬!

mysql中生成时间维度表

       利用mysql常用日期函数生成时间维度表,效率最高,最简单,无需其他的一些工具支持。生成结果示例如下图:

复制下面的运行,就ok,和运行平常的sql语句一样!

  
  
  1. # time span
  2. SET @d0 = "2012-01-01";
  3. SET @d1 = "2012-12-31";
  4. SET @ date = date_sub(@d0, interval 1 day);
  5. # set up the time dimension table
  6. DROP TABLE IF EXISTS time_dimension;
  7. CREATE TABLE `time_dimension` (
  8. `date` date DEFAULT NULL,
  9. `id` int NOT NULL,
  10. `y` smallint DEFAULT NULL,
  11. `m` smallint DEFAULT NULL,
  12. `d` smallint DEFAULT NULL,
  13. `yw` smallint DEFAULT NULL,
  14. `w` smallint DEFAULT NULL,
  15. `q` smallint DEFAULT NULL,
  16. `wd` smallint DEFAULT NULL,
  17. `m_name` char( 10) DEFAULT NULL,
  18. `wd_name` char( 10) DEFAULT NULL,
  19. PRIMARY KEY ( `id`)
  20. );
  21. # populate the table with dates
  22. INSERT INTO time_dimension
  23. SELECT @ date := date_add(@ date, interval 1 day) as date,
  24. # integer ID that allowsimmediate understanding
  25. date_format(@ date, "%Y%m%d") as id,
  26. year(@ date) as y,
  27. month(@ date) as m,
  28. day(@ date) as d,
  29. date_format(@ date, "%x") as yw,
  30. week(@ date, 3) as w,
  31. quarter(@ date) as q,
  32. weekday(@ date)+ 1 as wd,
  33. monthname(@ date) as m_name,
  34. dayname(@ date) as wd_name
  35. FROM T
  36. WHERE date_add(@ date, interval 1 day) <= @d1
  37. ORDER BY date
  38. ;


       神秘的表T,仅仅需要有多于你需要生成日期的记录数即可。思路是从T表选择多行数据,同时生成对应的日期字段。

这里对转载的解释一下:表T可以是任意表,只要记录数比你要生成的天数多就可以了。比如上面的2012-01-01到2012-12-31,只要记录数大于366条就可以!!

猜你喜欢

转载自blog.csdn.net/qq_25833195/article/details/88998819
今日推荐