How to generate data in MySQL?

后端 未结 4 1667

Here is my SQL:

SELECT 
  COUNT(id),
  CONCAT(YEAR(created_at), \'-\', MONTH(created_at), \'-\', DAY(created_at))
FROM my_table
GROUP BY YEAR(created_at), MO         


        
4条回答
  •  无人及你
    2020-11-27 09:00

    SQL is notoriously bad at returning data that is not in the database. You can find the beginning and ending values for gaps of dates, but getting all the dates is hard.

    The solution is to create a calendar table with one record for each date and OUTER JOIN it to your query.

    Here is an example assuming that created_at is type DATE:

    SELECT calendar_date, COUNT(`id`)
    FROM calendar LEFT OUTER JOIN my_table ON calendar.calendar_date = my_table.created_at
    GROUP BY calendar_date
    

    (I'm guessing that created_at is really DATETIME, so you'll have to do a bit more gymnastics to JOIN the tables).

提交回复
热议问题