Mysql

关注公众号 jb51net

关闭
首页 > 数据库 > Mysql > MySQL日期维度表

MySQL生成日期维度表的sql语句

作者:ronshi

这篇文章主要介绍了MySQL生成日期维度表的sql语句,通过存储过程生成,其次是通过递归的公用表表达式生成,需要的朋友可以参考下

MySQL生成日期维度表

1、通过存储过程生成

DELIMITER $$
CREATE PROCEDURE dateDim(startDate DATE, endDate DATE)  
BEGIN  
    DECLARE currentDate DATE;  
    SET currentDate = startDate;  
    WHILE currentDate <= endDate DO  
        INSERT INTO sys_calendar (stats_day) VALUES (currentDate);  
        SET currentDate = DATE_ADD(currentDate, INTERVAL 1 DAY);  
    END WHILE;  
END $$
DELIMITER ;  
CALL dateDim('2022-01-01', '2030-12-31');

2、通过递归的公用表表达式生成

WITH RECURSIVE date_series AS (  
  SELECT '2023-01-01' AS date_value  
  UNION ALL  
  SELECT DATE_ADD(date_value, INTERVAL 1 DAY)  
  FROM date_series  
  WHERE date_value < '2023-12-31'  
)  
INSERT INTO date_dim (date_value)  
SELECT date_value FROM date_series;

补充:Mysql 快速生成日期时间维度表

Mysql 快速生成日期时间维度表

创建表结构

CREATE TABLE `dim_date` (
  `id` int(11) NOT NULL COMMENT '日期键 20000101',
  `date` date DEFAULT NULL COMMENT '日期 2000-01-01',
  `year` smallint(6) DEFAULT NULL COMMENT '年 2000',
  `month` smallint(6) DEFAULT NULL COMMENT '月 01',
  `day` smallint(6) DEFAULT NULL COMMENT '日 01',
  `quarter` smallint(6) DEFAULT NULL COMMENT '当年所属季度',
  `year_of_week` smallint(6) DEFAULT NULL COMMENT '当前周所属年份',
  `week` smallint(6) DEFAULT NULL COMMENT '当年所属周',
  `day_of_week` smallint(6) DEFAULT NULL COMMENT '星期几',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

生产数据

SET @d0 = '2000-01-01';
SET @d1 = '2100-12-31';
SET @date = DATE_SUB( @d0, INTERVAL 1 DAY );
INSERT INTO `dim_date`(`date`, `id`,  `year`, `month`, `day`, `quarter`, `year_of_week`, `week`, `day_of_week`) 
SELECT
@date := DATE_ADD( @date, INTERVAL 1 DAY ) AS DATE,
DATE_FORMAT( @date, '%Y%m%d' ) AS id,
YEAR ( @date ) AS Y,
MONTH ( @date ) AS m,
DAY ( @date ) AS d,
QUARTER ( @date ) AS q,
DATE_FORMAT( @date, '%x' ) AS yw,
WEEK ( @date, 3 ) AS w,
WEEKDAY( @date ) + 1 AS wd
FROM
	[某张行数比日期差大的表]
WHERE
	DATE_ADD( @date, INTERVAL 1 DAY ) <= @d1 
ORDER BY
	DATE;

到此这篇关于MySQL生成日期维度表的文章就介绍到这了,更多相关MySQL日期维度表内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文