要求:统计表中最近30日(包括今日)的数据,如果数据没有,则以0代替
方式一:显示所有日期列表,无数据时补0
SQL语句如下:
select t.date as overThirtyDays,
IFNULL(SUM(case when DATE_FORMAT(ct.create_time,'%Y-%m-%d')=t.date then 1 else 0 end),0) as userTaskCountEveryDay
from (
select DATE_FORMAT(DATE_SUB(NOW(),INTERVAL xc DAY),'%Y-%m-%d') as date
from (
select @xi:=@xi+1 as xc from
(select 1 UNION select 2 UNION select 3 UNION select 4 UNION select 5) xc1,
(select 1 UNION select 2 UNION select 3 UNION select 4 UNION select 5 UNION select 6) xc2,
(select @xi:=-1) xc0
) tt) t,t_capture_task ct
where ct.node_code='user_100'
group by t.date;
说明
1、当前时间为:2019-09-27,当xc0中的xi为-1时,则从2019-08-292019-09-27;当xi为0时,则从2019-08-282019-09-26
2、xc1与xc2为定义数据条数:5*6=30,即查询30天的数据
3、DATE_SUB(NOW(),INTERVAL xc DAY),'%Y-%m-%d'
为定义数据拓展规律,NOW()是表示当前日期,INTERVAL xc DAY
表示根据变量xc的值变化,如果xc是1,那么就当前日往前推1。
如下图:

方式二:只显示有数据的日期
select DATE_FORMAT(create_time,'%Y-%m-%d') as overThirtyDays
,count(1) as userTaskCountEveryDay
from t_capture_task
where create_time > DATE_FORMAT(DATE_SUB(NOW(),INTERVAL 30 DAY),'%Y-%m-%d')
and node_code='user_100'
GROUP BY DATE_FORMAT(create_time,'%Y-%m-%d');
如下图

网友评论