我需要从一张警报记录表中统计一整年里每个月的不同类型的数量,表中字段主要为id, alarm_type以及alarm_time,因为alarm_time是时间戳,我不知道要如何处理来将这些时间戳分类,还有一个难点就是我想要返回的结果是alarm_type,alarm_count以及该警报类型属于的那个月一号零点的时间戳
解决方案
分步骤说吧
把时间戳转成时间
`select from_unixtime(alarm_time) `;
按月统计的话,就要把时间转成月
`select date_format( from_unixtime(alarm_time),"%Y%m")`;
- 最后的SQL可能会是这个样子
select count(t.id) as 'alarm_count',t.type as 'alarm_type' from( select id,alarm_type ,date_format( from_unixtime(alarm_time),"%Y%m")` as time from tablename ) t group by t.time,t.alarm_type
- 我又重新审视了下题主的要求,为了查出所属月的凌晨时间戳,所以在上一步的基础上改一下SQL
select count(t.id) as 'alarm_count',t.type as 'alarm_type',unix_timestamp(str_to_date(t.time,"%Y%M")) as 'alarm_time' from( select id,alarm_type ,date_format( from_unixtime(alarm_time),"%Y%m")` as time from tablename ) t group by t.time,t.alarm_type