MySQL Query GROUP BY day / month / year

Fernando Barrocal picture Fernando Barrocal · Feb 3, 2009 · Viewed 670.2k times · Source

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:

SELECT COUNT(id)
FROM stats
WHERE record_date.YEAR = 2009
GROUP BY record_date.YEAR

Or even:

SELECT COUNT(id)
FROM stats
GROUP BY record_date.YEAR, record_date.MONTH

To have a monthly statistic.

Thanks!

Answer

codelogic picture codelogic · Feb 3, 2009
GROUP BY YEAR(record_date), MONTH(record_date)

Check out the date and time functions in MySQL.