# 统计一年中每个月的数据,如果该月没有数据则显示0 withrecursive months as (select1asmonth unionall selectmonth+1 from months wheremonth<12) select months.month,COALESCE(t2.cnt,0) as count from months leftjoin (selectcount(1) as cnt, month(alarmtime) asmonth from forest_fireproof.alarm_info where alarmtime between'2025-01-01'and'2025-12-31' groupbymonth(alarmtime)) t2 on months.month = t2.month;
示例2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 从当前月份往前推11个月,统计历史数据趋势,没有数据则显示0 WITHRECURSIVE months AS ( SELECT DATE_FORMAT(DATE_SUB(CURRENT_DATE, INTERVAL11MONTH), '%Y-%m-01') AS month_date UNIONALL SELECT DATE_FORMAT(DATE_ADD(month_date, INTERVAL1MONTH), '%Y-%m-01') FROM months WHERE month_date < DATE_FORMAT(CURRENT_DATE, '%Y-%m-01') ) SELECT DATE_FORMAT(m.month_date, '%Y-%m') ASmonth, IFNULL(COUNT(e.id), 0) AS event_count FROM months m LEFTJOIN zjg_event_info e ON DATE_FORMAT(e.create_time, '%Y-%m') = DATE_FORMAT(m.month_date, '%Y-%m') AND (e.event_type ='3'or (e.event_type ='2'and e.scope_flag ='1')) GROUPBYmonth ORDERBYmonth;