1. 程式人生 > >mysql 根據某一年 查詢12個月的資料

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'

效果:

 

 

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