我正在尝试根据注册和取消日期计算活跃的每月用户数。有几个用户有NULL取消日期(因为仍然有效)。此查询有一堆用户,只是null action_year和action_month。
SELECT
T.action_year,
T.action_month,
COUNT(USerID) active_users
FROM
(
SELECT DISTINCT UserID, YEAR(SignupDate) action_year, MONTH(SignupDate) action_month FROM Stat
UNION
SELECT DISTINCT UserID, YEAR(CancelDate) action_year, MONTH(CancelDate) action_date FROM Stat
) T
GROUP BY
T.action_year,
T.action_month
ORDER BY
T.action_year ASC,
T.action_month ASC
答案 0 :(得分:1)
据推测,活跃用户是月份以某种方式在注册和取消日期之间的用户。这很难定义。它在本月的任何日期都有效吗?活动在最后一天?第一天活动?
我将假设第一个。在这个月的任何一天都很活跃。
这个想法是,给定月份中的活动数量都是先前已注册但尚未停止的人数。鉴于此观察结果,计算如下:
CancelDate
可以是NULL
。生成的查询是:
select ym.the_year, ym.the_month,
(select count(*)
from stat s
where date_format(SignupDate, '%Y-%m') <= ym.yyyymm and
(CancelDate is null or date_format(CancelDate, '%Y-%m') >= ym.yyyymm)
) as NumActives
from (select distinct year(SignupDate) as the_year, month(SignupDate) as the_month,
date_format(SignupDate, '%Y-%m') as yyyymm
from stat
) ym