Mysql to select month-wise record even if data not exist

前端 未结 2 1832
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 22:14

I wrote a query to get month-wise record in user table as follows

SELECT COUNT( `userID` ) AS total, DATE_FORMAT( `userRegistredDate` , \'%b\' ) AS
MONTH , Y         


        
2条回答
  •  感动是毒
    2020-11-27 22:30

    You may need a table to hold every "month" record. A temp table can do the trick:

    drop table if extists temp_months;
    create temporary table temp_months
        month date,
        index idx_date(month);
    insert into temp_months
        values ('2013-01-31'), ('2013-02-28'), ...
    

    And now, you can left join your data with this newly created temp table:

    SELECT 
        COUNT( `userID` ) AS total, 
        DATE_FORMAT( m.month , '%b' ) AS
        MONTH , 
        YEAR( m.month ) AS year
    FROM 
        months as m
        left join `users` as u on m.month = last_day(FROM_UNIXTIME(`userRegistredDate`, '%b' )
    GROUP BY 
        last_day(m.month);
    

    Notice that you can put the temp table creation (and fill) in a stored procedure.

    I use last_day for simplicity, but you are free to use any date in the month that you like, if you join it correctly.

    Hope this helps

提交回复
热议问题