在MySQL中滚动计数

时间:2011-05-31 09:24:38

标签: mysql

我需要获得以下比率(每日注册计数)/(每天滚动注册计数的最后30天)

每日数字很直接

SELECT a.DailySignup
FROM
(
SELECT COUNT(1) AS DailySignup, date
FROM users
WHERE date BETWEEN datestart and dateend
GROUP BY date
) a

但我如何计算每天最近30天的数量呢?我知道我需要再次在同一张桌子上加入它,但我似乎无法围绕它如何围绕它。

更新 对不起,我不是很清楚。

SIGNUP_COUNT DATE          Rolling_Signup_Count
10           2011-01-01    Sign ups from 2010-12-01 to 2011-01-01
12           2011-01-02    Sign ups from 2010-12-02 to 2011-01-02
4            2011-01-03    Sign ups from 2010-12-03 to 2011-01-03

希望此表有助于说明滚动注册计数的含义

2 个答案:

答案 0 :(得分:2)

您可以尝试子查询:

SELECT DISTINCT t.date, 
(SELECT COUNT(*) FROM users u where u.date BETWEEN DATE_ADD(t.date, INTERVAL -30 day) AND t.date) as c 
FROM users t

对于给定日期t.date,子查询计算以t.date结尾的30天期间的计数。

编辑:要计算比率(每天登录次数)/(30天内登录),您可以尝试

SELECT t.date, count(*)/(SELECT COUNT(*) FROM users u 
       WHERE u.date BETWEEN DATE_ADD(t.date, INTERVAL -30 day) AND t.date) as c 
FROM users t GROUP BY t.date

答案 1 :(得分:0)

您可以按MONTH(date)分组以获取每个月,尝试以下内容:

SELECT a.DailySignup, month AS MONTH(date)
FROM users
INNER JOIN (
    SELECT COUNT(*) AS DailySignup, MONTH(date) AS month
            FROM users
    GROUP BY MONTH(date)
) a ON a.month = month
    GROUP BY month