本文主要是介绍mysql 日期取近七天、当前周七天 数据(补全空数据) 简单案例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
首先我们新建一张测试表格,date_day为日期,score为成绩,表格名ceshi。
我们如果取近七天的每天总成绩数据,常用的sql应该是:
SELECT date_day,sum(score) as score FROM ceshi WHERE DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(date_day) GROUP BY date_day ORDER BY date_day
执行结果为:
这样虽然得出了结果,但是如果数据库里没有完整的7天数据,那么他只能得到已有的三天数据。
所以我们需要改一下sql,关联一张自己创建的7天日期临时表:
select d.date, IFNULL(T.score,0) socre from
(SELECT CURDATE() AS dateUNION ALLSELECT DATE_SUB(CURDATE(), INTERVAL 1 DAY) AS dateUNION ALLSELECT DATE_SUB(CURDATE(), INTERVAL 2 DAY) AS dateUNION ALLSELECT DATE_SUB(CURDATE(), INTERVAL 3 DAY) AS dateUNION ALLSELECT DATE_SUB(CURDATE(), INTERVAL 4 DAY) AS dateUNION ALLSELECT DATE_SUB(CURDATE(), INTERVAL 5 DAY) AS dateUNION ALLSELECT DATE_SUB(CURDATE(), INTERVAL 6 DAY) AS date
) d
left join(select date_day, sum(score) as scorefrom ceshigroup by DATE_FORMAT(date_day,'%Y-%m-%d')
) T on T.date_day = d.date
GROUP BY d.date
执行结果为 :
同理 如果我们想要得到本周7天的数据,那么只需要改下日期临时表格,
select d.date, IFNULL(T.score,0) socre from
(select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) + 0 DAY) as date
UNION ALL
select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) - 1 DAY) as date
UNION ALL
select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) - 2 DAY) as date
UNION ALL
select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) - 3 DAY) as date
UNION ALL
select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) - 4 DAY) as date
UNION ALL
select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) - 5 DAY) as date
UNION ALL
select date_sub(curdate(),INTERVAL WEEKDAY(curdate()) - 6 DAY) as date
) d
left join(select date_day, sum(score) as scorefrom ceshigroup by DATE_FORMAT(date_day,'%Y-%m-%d')
) T on T.date_day = d.date
GROUP BY d.date
执行结果为:
这篇关于mysql 日期取近七天、当前周七天 数据(补全空数据) 简单案例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!