1

I'm trying to return the count of records within each month and group the result by month / year.

Schema looks something like this:

id    title    timestamp

I've been searching around but I can't get the result as I expect it. Thanks.

1
  • You want to count Jan/2010 and Jan/2011 separately, right? Commented May 28, 2011 at 10:25

2 Answers 2

7

Format the timestamp, then group by it.

Group by Month:

SELECT DATE_FORMAT(t.timestamp, "%Y-%m") AS "_Month", COUNT(*)
FROM yourtable as t
GROUP BY _Month;

Group by Year:

SELECT DATE_FORMAT(t.timestamp, "%Y") AS "_Year", COUNT(*)
FROM yourtable as t
GROUP BY _Year;

If the timestamp-field is stored as a unixtime-value, just wrap FROM_UNIXTIME() around the field:

SELECT DATE_FORMAT(FROM_UNIXTIME(t.timestamp), "%Y") AS "_Year", COUNT(*)
FROM yourtable as t
GROUP BY _Year;
Sign up to request clarification or add additional context in comments.

Comments

3
SELECT YEAR(`timestamp`) AS Y, MONTH(`timestamp`) AS M, COUNT(1) AS C
FROM that_table
GROUP BY YEAR(`timestamp`), MONTH(`timestamp`)
ORDER BY YEAR(`timestamp`), MONTH(`timestamp`)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.