我最终使用了一个包含变量的解决方案,基于此处发布的 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;