1. 程式人生 > >mysql 根據起止年月 查詢所選年月的資料

mysql 根據起止年月 查詢所選年月的資料

1、時間欄位是datetime型別

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

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

3、前兩個 adddate 日需要在資料庫寫死 從每日的-01開始,-最後一個日期同理xxxx-xx-31

4、sql

select
    bri.orgid,
    years.date,
    date_format(years.date, '%Y-%m') AS years,
    bri.entrytime a,
    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-10-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-10-01', INTERVAL numlist.id month) <= '2019-05-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、結果

 

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