【MySQL】统计某一年中各个月的数据总和

需求

根据年份,统计12个月的每月行驶公里总和数

解决

select sum(case month(begin_time) when '1' then total_mileage else 0 end) as 1,
sum(case month(begin_time) when '2' then total_mileage else 0 end) as 2,
sum(case month(begin_time) when '3' then total_mileage else 0 end) as 3,
sum(case month(begin_time) when '4' then total_mileage else 0 end) as 4,
sum(case month(begin_time) when '5' then total_mileage else 0 end) as 5,
sum(case month(begin_time) when '6' then total_mileage else 0 end) as 6,
sum(case month(begin_time) when '7' then total_mileage else 0 end) as 7,
sum(case month(begin_time) when '8' then total_mileage else 0 end) as 8,
sum(case month(begin_time) when '9' then total_mileage else 0 end) as 9,
sum(case month(begin_time) when '10' then total_mileage else 0 end) as 10,
sum(case month(begin_time) when '11' then total_mileage else 0 end) as 11, 
sum(case month(begin_time) when '12' then total_mileage else 0 end) as 12from t_dmv_car_use_record  where car_id = '61999544314961100831801382360000'
and year(begin_time)='2022';

【MySQL】统计某一年中各个月的数据总和_第1张图片

说明

把 begin_time 换成你的时间字段,可以是create_time,update_time,根据实际需求来,但是这个字段一定是时间类型的
total_mileage字段换成你想要统计的字段,也是根据实际情况来

补充

  • 可以继续完善统计到今年当月的,但是我不会
  • 我的建议是:在service处理数据,保留当年从1月到当月的数据就行,这样不用修改sql,毕竟往年的数据都是一整年一整年的查。
  • 所以:如果只需要当年从1月到当月的数据,自己用代码处理一下

变式

上面这样获取的就是一行数据,有12列
能不能获取1列数据,但是有12行

select month(begin_time) as month,sum(total_mileage) 
from t_dmv_car_use_record
where year(begin_time) = "2022"  and car_id = '61843728643484467201050047260014'
group by month(begin_time)

【MySQL】统计某一年中各个月的数据总和_第2张图片
为空的月份不会显示,具体怎么改进展示没有思路

你可能感兴趣的:(分享,总结,mysql)