3

我有一个 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

其中“# of users”是截至给定日期注册帐户的用户总数(running-total)——而不是在特定日期注册的用户数(检索起来很简单)。

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

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

name: John Smith
uid: 526
created: 1365844220
4

3 回答 3

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在这里

于 2013-04-13T09:30:12.913 回答
3

我最终使用了一个包含变量的解决方案,基于此处发布的 Stack Overflow 答案。该解决方案似乎比提供的其他答案更灵活、更高效。

  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;
于 2013-04-14T11:36:08.557 回答
0

不知道表结构,所以根据您的需要调整查询

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

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

HAVING COUNT(*) > 0

在查询的和

于 2013-04-11T14:34:25.130 回答