Retrieve running-total record growth over time in mysql

陌路散爱 提交于 2019-12-04 13:14:37

Try:

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.

Jordan Magnuson

I ended up using a solution that incorporates variables, based on a Stack Overflow answer posted here. This solution appears to be a bit more flexible and efficient than other answers provided.

  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;

Note that the group by, date formatting, and range requirements are simply specifics of my particular project. A more generic form of this solution (as per the original question) would be:

  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;

Don't know the table structure so adjust the query to you needs

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

When you only want to show the dates having registerd users add

HAVING COUNT(*) > 0

At the and of the query

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