mysql如何统计一年里每个月里各个类型的数量

我需要从一张警报记录表中统计一整年里每个月的不同类型的数量,表中字段主要为id, alarm_type以及alarm_time,因为alarm_time是时间戳,我不知道要如何处理来将这些时间戳分类,还有一个难点就是我想要返回的结果是alarm_type,alarm_count以及该警报类型属于的那个月一号零点的时间戳

想要的结果大概是这样的

阅读 6k
2 个回答

分步骤说吧

  • 把时间戳转成时间

    `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

楼主最好把,数据贴出来,不然看不懂楼主最后一句的意思。
id, alarm_type,alarm_time
我看楼主字面上是要根据alarm_time按月统计出警报数量,可是后面看楼主说的
“以及该警报类型属于的那个月一号零点的时间戳”
这就不明白了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题