MySQL 根據某一年 查詢12個月的數據


1、時間字段是datetime類型

2、需要用到中間表,表結構和數據鏈接下載

鏈接:https://pan.baidu.com/s/1tAFU4nm1p4CkSneXwceA_A
提取碼:b3xi

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'

效果:

 

 

如有疏漏,請指正!謝謝。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM