MySQL 统计过去12个月的数据(包括本月),mysql本月
1、问题
需要统计过去12个月的数据,如现在是2015年4月,那么我们需要统计从2014年5月到2015年4月的数据情况。而这12个月中,如果这个月没有数据的,则统计为0。
原始数据表如下图,数据是按分钟存储的。也就是说要统计每个月一共有多少条body_infared大于0的数据。
2、处理过程
2.1 获取12个月到现在的数据
select * from device_data t where
DATE_FORMAT(t.time,'%Y-%m')>
DATE_FORMAT(date_sub(curdate(), interval 12 month),'%Y-%m');
2.2 统计某台设备在过去12个月中每个月body_infared大于0的数据之和。
select DATE_FORMAT(t.time,'%Y-%m') month,count(t.id) minute from device_data t
where t.body_infrared>0 and t.device_id=13
AND DATE_FORMAT(time,'%Y-%m')>
DATE_FORMAT(date_sub(curdate(), interval 12 month),'%Y-%m')
group by