SQL Count records within a month using a unix timestamp

丶灬走出姿态 提交于 2019-12-19 11:28:25

问题


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:


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;



回答2:


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`)


来源:https://stackoverflow.com/questions/6160990/sql-count-records-within-a-month-using-a-unix-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!