SQL Count records within a month using a unix timestamp

后端 未结 2 640
我寻月下人不归
我寻月下人不归 2021-01-16 10:23

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    t         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-16 10:47

    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;
    

提交回复
热议问题