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'

效果:

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

猜你喜欢

转载自www.cnblogs.com/w-yu-chen/p/10259374.html