首先我们新建一张测试表格,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 date
UNION ALL
SELECT DATE_SUB(CURDATE(), INTERVAL 1 DAY) AS date
UNION ALL
SELECT DATE_SUB(CURDATE(), INTERVAL 2 DAY) AS date
UNION ALL
SELECT DATE_SUB(CURDATE(), INTERVAL 3 DAY) AS date
UNION ALL
SELECT DATE_SUB(CURDATE(), INTERVAL 4 DAY) AS date
UNION ALL
SELECT DATE_SUB(CURDATE(), INTERVAL 5 DAY) AS date
UNION ALL
SELECT DATE_SUB(CURDATE(), INTERVAL 6 DAY) AS date
) d
left join(
select date_day, sum(score) as score
from ceshi
group 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 score
from ceshi
group by DATE_FORMAT(date_day,'%Y-%m-%d')
) T on T.date_day = d.date
GROUP BY d.date
执行结果为:
?
?
|