简体   繁体   English

如何编写一个计算每月和每年行数的SQL查询?

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

Had anyone any idea how to query a vbulletin database to generate a report on the number of registrations per month/year to achive results like.. 有没有人知道如何查询vbulletin数据库,以生成每月/每年注册数量的报告,以达到如下结果:

MM/YYYY      Count
01/2001  :   10
02/2001  :   12
...
...

Thanks to those answers below.. My final version that works is as follows: 感谢下面的答案。我的最终版本如下:

SELECT 
  COUNT(*) as 'Registrations', 
  YEAR(FROM_UNIXTIME(joindate)) as 'Year',
  MONTH(FROM_UNIXTIME(joindate)) as 'Month'
FROM vbfuser
GROUP BY Year,Month

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 . 我不熟悉vBulletin的数据库结构,但你应该做这样的事情 ,假设你的用户表有一个日期/日期时间/时间戳created_datereg_timestamp列或类似的东西,使用MySQL的YEAR()MONTH()函数

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. 编辑:关于戴夫的评论: vBulletin的日期似乎以Unixtime格式存储。 In this case, simply wrapping the column with FROM_UNIXTIME will convert it to a readable MySQL date: 在这种情况下,只需使用FROM_UNIXTIME包装列将其转换为可读的MySQL日期:

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. vBulletin保持每日统计数据,因此可以更好地处理该表。 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 ;) 如果您提供users表,它可能会更有帮助;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM