How to write an SQL query that counts the number of rows per month and year?

蓝咒 提交于 2019-12-04 11:16:39

I am not familiar with vBulletin's database structure, but you should do something like this, assuming your user table has a date/datetime/timestamp created_date or reg_timestamp column or something similiar, using MySQL's YEAR() and MONTH() functions.

select 
    count(*) as count, 
    year(reg_timestamp) as year 
    month(reg_timestamp) as month
from users 
group by year, month;

This will result in something similiar to this:

+-------+-------+------+
| count | month | year |
+-------+-------+------+
|     4 |    11 | 2008 | 
|     1 |    12 | 2008 | 
|   196 |    12 | 2009 | 
|   651 |     1 | 2010 | 
+-------+-------+------+

Edit: regarding Dave's comment: vBulletin's date seems to be stored in Unixtime format. In this case, simply wrapping the column with FROM_UNIXTIME will convert it to a readable MySQL date:

select 
    count(*) as count, 
    year(from_unixtime(reg_timestamp)) as year 
    month(from_unixtime(reg_timestamp)) as month
from users 
group by year, month;

vBulletin keeps daily stats, so it may be nicer to work off that table. It isn't much of a problem for counting new registrations but if you want to count posts it gets expensive eventually. Here's an example which does what you want:

SELECT
    DATE_FORMAT(FROM_UNIXTIME(dateline), '%m/%Y') AS month,
    SUM(nuser) AS new_users
FROM stats
GROUP BY month
ORDER BY dateline

You have to group by the field month:

select MONTHYEAR month , count(*) from tabname group by MONTHYEAR 

with this, you would read all monthyears and count the different rows, obtaining the info you need.

If you provide the users table, it could be of more help ;)

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