mysql 日期维度序列生成

建表语句:

CREATE TABLE `shence`.`Untitled`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `date` datetime NULL DEFAULT NULL,
  `dayid` int(11) NULL DEFAULT NULL,
  `weekid` int(11) NULL DEFAULT NULL,
  `monthid` int(11) NULL DEFAULT NULL,
  `quartid` int(11) NULL DEFAULT NULL,
  `yearid` int(11) NULL DEFAULT NULL,
  `y` int(11) NULL DEFAULT NULL,
  `m` int(11) NULL DEFAULT NULL,
  `d` int(11) NULL DEFAULT NULL,
  `yearmon` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
  `weekstr` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
  `quar` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
  `weekday` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
  `monname` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
  `dayname` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 

存储过程:

CREATE DEFINER=`root`@`%` PROCEDURE `dataauto`()
BEGIN

SET @d0 = "1970-01-01";
SET @d1 = "2050-12-31";
set @date = date_sub(@d0, interval 1 day);
set @dayid = 0;
set @monthid = 0;
set @weekid = 0;
set @cur_month = 0;
set @cur_week = 0;

INSERT INTO `shence`.`dim_shence` (`date`, `dayid`, `weekid`, `monthid`, `quartid`, `yearid`, `y`, `m`, `d`, `yearmon`, `weekstr`, `quar`, `weekday`, `monname`, `dayname`) 
VALUES ('1970-01-01 00:00:00', 0, 0, 0, 0, 0, 1970, 1, 1, '1970', '1', '1', '4', 'January', 'Thursday');

	while @date  <= @d1 DO
		#Routine body goes here...
		set @dayid=@dayid+1;
		set @date := date_add(@date, interval 1 day);
				
		if @cur_month=12 and month(@date) = 1 then 
			set @monthid = @monthid+1;
			set @cur_month = month(@date);
		elseif @cur_month < month(@date) then
			set @monthid = @monthid+1;
			set @cur_month = month(@date);
		END if;
		
		if @cur_week > week(@date, 3) THEN
			set @weekid = @weekid+1;
			set @cur_week = week(@date, 3);
		elseif @cur_week < week(@date, 3) then
			set @weekid = @weekid+1;
			set @cur_week = week(@date, 3);
		END if;		
		

		insert into dim_shence(date,y,m,d,yearmon,weekstr,quar,weekday,monname,dayname,dayid,monthid,weekid) 
		select @date as date  ,
		year(@date) as y,
		month(@date) as m,
		day(@date) as d,
		date_format(@date, "%x")as yearmon,
		week(@date, 3) as weekstr,
		quarter(@date) as quar,
		weekday(@date)+1 as weekday,
		monthname(@date) as monname,
		dayname(@date) as dayname,
		@dayid as dayid,
		@monthid as monthid,
		@weekid as weekid
		from dim_shence
		where @date <= @d1
		ORDER BY date desc
		limit 1;
	END WHILE;
END

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值