mysql 根据某一年 查询12个月的数据

Posted w-yu-chen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql 根据某一年 查询12个月的数据相关的知识,希望对你有一定的参考价值。

1、时间字段是datetime类型

2、需要用到中间表,表结构和数据链接下载

https://pan.baidu.com/s/1sAQ78e3Ao-KwvYJlaipbKQ

3、前两个 adddate 月日需要在数据库写死 从每年的-01-01开始,-最后一个日期同理xxxx-12-31

4、下面是sql

select
    concat(month(years.date),) as year,
    years.date,
    date_format(years.date, %Y-%m) AS years,
    sum( case when bri.status = 1 then 1 else 0 end ) as num, -- 总数
    sum( case when bri.status = 1 and bri.sex=1 then 1 else 0 end  ) as numman, -- 男性数量
    sum( case when bri.status = 1 and bri.sex=2 then 1 else 0 end  ) as numgrid -- 女性数量
    
from
    ( select adddate(2018-01-01, INTERVAL numlist.id month) as date, numlist.id 
    from ( select n100.i * 1 as id from num as n100 ) as numlist 
    where adddate(2018-01-01, INTERVAL numlist.id month) <= 2018-12-31 ) years
    
left join building_resident_info bri on date_format(years.date, %Y-%m)  = date_format(bri.entrytime, %Y-%m) and bri.status=1

and bri. status = 1
and bri.orgid like concat(37.02.82, %)
group by years.date

5、效果图如下

技术分享图片

 

附带:

1、还有一种写法,是把12个月写死的

sql:

select
case month(bri.entrytime) when 1 then sum(bri.status) else 0 end as 1月,
case month(bri.entrytime) when 2 then sum(bri.status) else 0 end as 2月,
case month(bri.entrytime) when 3 then sum(bri.status) else 0 end as 3月,
case month(bri.entrytime) when 4 then sum(bri.status) else 0 end as 4月,
case month(bri.entrytime) when 5 then sum(bri.status) else 0 end as 5月,
case month(bri.entrytime) when 6 then sum(bri.status) else 0 end as 6月,
case month(bri.entrytime) when 7 then sum(bri.status) else 0 end as 7月,
case month(bri.entrytime) when 8 then sum(bri.status) else 0 end as 8月,
case month(bri.entrytime) when 9 then sum(bri.status) else 0 end as 9月,
case month(bri.entrytime) when 10 then sum(bri.status) else 0 end as 10月,
case month(bri.entrytime) when 11 then sum(bri.status) else 0 end as 11月,
case month(bri.entrytime) when 12 then sum(bri.status) else 0 end as 12月


from building_resident_info bri


where date_format(bri.entrytime, %Y) = 2018
and bri.orgid like concat(37.02.82.01, %) 
and bri.status=1

效果:

 

技术分享图片

 

如有疏漏,请指正!谢谢。

以上是关于mysql 根据某一年 查询12个月的数据的主要内容,如果未能解决你的问题,请参考以下文章

如何用sql的日期函数,分别查出1月~12月每个月的销售金额?

Oracle统计某一年中的1-12个月的数据总和

查询近7天,近1个月,近3个月每天的数据量,查询近一年每个月的数据量

php+mysql中怎么查询最近12个月每个月的数据

取上个月和上一年的数据,sql怎么写

mysql 查询统计! 我要统计12个月的数据!