Grouping MySQL query by date

Working on a statistics plugin I needed a way to group records by the day.  Turns out it’s remarkably easy.

SELECT COUNT(id), theDate FROM table GROUP BY YEAR(theDate), MONTH(theDate), DAY(theDate);

If you just want to group by year and month take off the DAY() part.  This would also be a good query to use WEEK() on to pull records grouped by the week they were posted.

This entry was posted in Computers & Internet and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>