1、问题
需要统计过去12个月的
原始数据表如下图,数据是按分钟存储的。也就是说要统计每个月一共有多少条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 device_id,month
获取结果: