mysql 时间段查询,无数据时补0

时间:2022-09-26 11:22:02
CREATE TABLE num (i int);  

INSERT INTO num (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);


创建临时表(这里是0~9999)一万条根据需要修改

SELECT n1.i + n10.i*10 + n100.i*100 + n1000.i*1000 AS id FROM num n1 cross join num as n10 cross join num as n100 cross join num as n1000


利用adddate函数,将日期向上累加直到你的enddate

select adddate('2017-09-01 00:00:00',INTERVAL numlist.id HOUR) as date,0 as faultNum from (
SELECT n1.i + n10.i*10 + n100.i*100 + n1000.i*1000 AS id FROM num n1 cross join num as n10 cross join num as n100 cross join num as n1000) as numlist
where adddate('2017-09-01 00:00:00', INTERVAL numlist.id HOUR) <= '2018-09-01 00:00:00'