Mysql時間維度表

1、建一張表test_date用來日期的自增長,裏面只放一列  ID,寫一個存儲,插入順序數字

BEGIN
#Routine body goes here...

declare id int;
set id=1;
while id<=6000 do
insert into test_date
values(id);
set id=id+1;
end while;
END

2. 建立時間維度表,插入記錄

SET @d0 = "2000-01-01";
SET @d1 = "2020-12-31"; 
SET @str = "Q"; 
SET @date = date_sub(@d0, interval 1 day);

INSERT INTO dim_time
SELECT @date := date_add(@date, interval 1 day),    
  year(@date),
  month(@date),
  DAYOFYEAR(@date),
  day(@date) as d,
  weekday(@date)+1 as wd,
  week(@date, 3) as w,
  dayname(@date) as wd_name,
  monthname(@date) as m_name, 
  quarter(@date) as q,
  CONCAT(@str,quarter(@date)) as qq,
  DAYOFMONTH(last_day(@date)),
  date_format(@date, "%Y%m%d"),    
  date_format(@date, '%d-%m-%Y')as yw
FROM test_date
WHERE date_add(@date, interval 1 day) <= @d1
ORDER BY id;


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章