在mysql中检索随时间推移的运行总记录增长

时间:2013-04-11 14:16:27

标签: mysql count running-total

我有一个Drupal站点,它有一个跟踪用户的表。我想要做的是随着时间的推移图表成员增长。所以我想按摩mysql来返回这样的东西:

date | # of users (total who have registered up to the given date)
1/1/2014 | 0
1/2/2014 | 2
1/3/2014 | 10

“用户数”是指在指定日期之前注册帐户的用户总数(运行总计) - 不是在该特定日期注册的用户数(这是很容易检索的。)

我的{users}表的每一行都有一个uid列,一个name列和一个created(时间戳)列。

因此,我{users}表中的示例记录将是:

name: John Smith
uid: 526
created: 1365844220

3 个答案:

答案 0 :(得分:5)

尝试:

select u.created, count(*)
from (select distinct date(created) created from `users`) u
join `users` u2 on u.created >= date(u2.created)
group by u.created

SQLFiddle here

答案 1 :(得分:3)

我最终使用了一个包含变量的解决方案,基于发布的帖子溢出答案here。此解决方案似乎比其他答案更灵活,更有效。

  SELECT u.date,
  @running_total := @running_total + u.count AS count
  FROM (
    SELECT COUNT(*) AS count, DATE_FORMAT(FROM_UNIXTIME(created), '%b %d %Y') AS date
    FROM {users}
    WHERE created >= :start_time AND created <= :end_time
    GROUP BY YEAR(FROM_UNIXTIME(created)), MONTH(FROM_UNIXTIME(created)), DAY(FROM_UNIXTIME(created))
  ) u
  JOIN (
    SELECT @running_total := u2.starting_total
    FROM (
      SELECT COUNT(*) as starting_total
      FROM {users}
      WHERE created < :start_time
    ) u2
  ) initialize;

请注意,分组依据,日期格式和范围要求只是我特定项目的细节。 此解决方案的更通用形式(根据原始问题)将是:

  SELECT u.date,
  @running_total := @running_total + u.count AS count
  FROM (
    SELECT COUNT(*) AS count, DATE(FROM_UNIXTIME(created)) AS date
    FROM {users}
    GROUP BY date
  ) u
  JOIN (
    SELECT @running_total := 0
  ) initialize;

答案 2 :(得分:0)

不知道表格结构,因此根据需要调整查询

SELECT DATE(created), COUNT(*) AS Users FROM users GROUP BY DATE(created)

当您只想显示已注册用户的日期时添加

HAVING COUNT(*) > 0

在查询和