Saturday, October 9, 2010

MySQL Query GROUP BY day / month / year

Wow I just found the most awesome thing with MySQL. I've always needed to group date data by month and year and never knew you could do it via SQL so easy.

Here's someones question:

"Heyall,
Is it possible I 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!"

And the response:


GROUP BY YEAR(record_date), MONTH(record_date)
Check out the date and time functions in MySQL.


Ref: http://stackoverflow.com/questions/508791/mysql-query-group-by-day-month-year

No comments:

Followers