MySQL Query GROUP BY day / month / year

前端 未结 14 2356
野趣味
野趣味 2020-11-22 06:37

Is it possible to make a simple query to count how many records I have in a determined period of time like a year, month, or day, having a TIMESTAMP field, like

相关标签:
14条回答
  • 2020-11-22 06:51
    GROUP BY YEAR(record_date), MONTH(record_date)
    

    Check out the date and time functions in MySQL.

    0 讨论(0)
  • 2020-11-22 06:54

    I prefer to optimize the one year group selection like so:

    SELECT COUNT(*)
      FROM stats
     WHERE record_date >= :year 
       AND record_date <  :year + INTERVAL 1 YEAR;
    

    This way you can just bind the year in once, e.g. '2009', with a named parameter and don't need to worry about adding '-01-01' or passing in '2010' separately.

    Also, as presumably we are just counting rows and id is never NULL, I prefer COUNT(*) to COUNT(id).

    0 讨论(0)
  • 2020-11-22 06:55

    .... group by to_char(date, 'YYYY') --> 1989

    .... group by to_char(date,'MM') -->05

    .... group by to_char(date,'DD') --->23

    .... group by to_char(date,'MON') --->MAY

    .... group by to_char(date,'YY') --->89

    0 讨论(0)
  • 2020-11-22 06:58

    If you want to group by date in MySQL then use the code below:

     SELECT COUNT(id)
     FROM stats
     GROUP BY DAYOFMONTH(record_date)
    

    Hope this saves some time for the ones who are going to find this thread.

    0 讨论(0)
  • 2020-11-22 07:00

    Complete and simple solution with similarly performing yet shorter and more flexible alternative currently active:

    SELECT COUNT(*) FROM stats
    -- GROUP BY YEAR(record_date), MONTH(record_date), DAYOFMONTH(record_date)
    GROUP BY DATE_FORMAT(record_date, '%Y-%m-%d')
    
    0 讨论(0)
  • 2020-11-22 07:01

    I tried using the 'WHERE' statement above, I thought its correct since nobody corrected it but I was wrong; after some searches I found out that this is the right formula for the WHERE statement so the code becomes like this:

    SELECT COUNT(id)  
    FROM stats  
    WHERE YEAR(record_date) = 2009  
    GROUP BY MONTH(record_date)
    
    0 讨论(0)
提交回复
热议问题