Skip to content

Instantly share code, notes, and snippets.

@jesstess
Created December 22, 2010 04:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesstess/751074 to your computer and use it in GitHub Desktop.
Save jesstess/751074 to your computer and use it in GitHub Desktop.
Quick frequency tables bucketing on time in MySQL
# date field is of type 'date'
mysql> SELECT YEAR(date) AS year, MONTH(date) AS month, count(*) AS count FROM my_table GROUP BY year, month ORDER BY year, month;
+------+-------+-------+
| year | month | count |
+------+-------+-------+
| 2008 | 6 | 1 |
| 2009 | 3 | 1 |
| 2009 | 5 | 2 |
| 2009 | 6 | 1 |
| 2009 | 7 | 1 |
| 2009 | 8 | 5 |
| 2009 | 9 | 10 |
| 2009 | 10 | 7 |
| 2009 | 11 | 35 |
| 2009 | 12 | 38 |
| 2010 | 1 | 39 |
| 2010 | 2 | 219 |
| 2010 | 3 | 129 |
| 2010 | 4 | 132 |
| 2010 | 5 | 107 |
| 2010 | 6 | 71 |
| 2010 | 7 | 102 |
| 2010 | 8 | 84 |
| 2010 | 9 | 671 |
| 2010 | 10 | 227 |
| 2010 | 11 | 161 |
| 2010 | 12 | 167 |
+------+-------+-------+
http://dev.mysql.com/doc/mysql/en/date-and-time-functions.html list all the ways to dissect a 'date' type. Other options include the day of the week, month, or year, the quarter, and the week of the year.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment