mysql生成日期表

統(tǒng)計數(shù)據(jù)時,如果交易數(shù)據(jù)不是連續(xù)的,比如統(tǒng)計每天的銷售額,某個日期對應節(jié)假日,銷售額=0,這樣輸出的數(shù)據(jù)是不連續(xù)的。為了解決這個問題,我們可以提前生成一個日期表,沒有數(shù)據(jù)的日期填充0即可。
具體步驟如下:

1、創(chuàng)建一個num表,用來存儲數(shù)字0-9
create table num(i int);
2、在num表生成0-9
insert into num(i) values(0), (1), (2), (3), (4), (5), (6), (7), (8), (9);
3、生成一個存儲日期的表,datelist是字段名
create table if not exists calendar(datelist date);
4、插入日期數(shù)據(jù)
INSERT INTO calendar
    (datelist
    )
SELECT
    adddate((date_format('2015-01-01', '%Y-%m-%d')), numlist.id) AS DATE,
FROM
    (
        SELECT
            n1.i + n10.i * 10 + n100.i * 100 + n1000.i * 1000 + n10000.i * 10000 AS id
        FROM
            num n1
        CROSS JOIN num AS n10
        CROSS JOIN num AS n100
        CROSS JOIN num AS n1000
        CROSS JOIN num AS n10000
    ) AS numlist;
5、最后,添加主鍵
ALTER TABLE `calendar`
ADD COLUMN `id`  int UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主鍵' FIRST ,
ADD PRIMARY KEY (`id`);

到這里,日期表已經(jīng)建好了,統(tǒng)計數(shù)據(jù)的時候關聯(lián)該表即可。

附:tidb創(chuàng)建日期表語句示例

-- 創(chuàng)建一個num表,用于存儲0-9
drop table if EXISTS test.temp_num;
CREATE TABLE test.temp_num (
`i`  int(10) NOT NULL 
)
;
INSERT INTO test.temp_num (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);
select * from test.temp_num;

-- 創(chuàng)建日期表
drop table if EXISTS test.temp_calendar;
CREATE TABLE test.temp_calendar (
`id`  int(10) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`datelist`  date NULL DEFAULT NULL 
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8mb4 COLLATE=utf8mb4_bin
ROW_FORMAT=COMPACT 
;

-- 插入日期數(shù)據(jù)
INSERT INTO test.temp_calendar
    (datelist
    )
SELECT
    adddate((date_format('2015-01-01', '%Y-%m-%d')), numlist.id1) AS DATE
FROM
    (
        SELECT
            n1.i + n10.i * 10 + n100.i * 100 + n1000.i * 1000 + n10000.i * 10000 AS id1
        FROM
            test.temp_num n1
        CROSS JOIN test.temp_num AS n10
        CROSS JOIN test.temp_num AS n100
        CROSS JOIN test.temp_num AS n1000
        CROSS JOIN test.temp_num AS n10000
        order by id1 asc 
    ) AS numlist;
select * from test.temp_calendar order by datelist desc limit 10;
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容