我有一个用户活动表。
created_at account_id
2017-01-01 1221
2017-01-01 21458
2017-01-03 1221
2017-01-04 1221
2017-01-04 4555
....
现在我获得使用此查询在特定一周内处于活动状态的唯一身份用户数(account_id)。
SELECT YEARWEEK(created_at) as yearweek, COUNT(DISTINCT account_id) as count
FROM activities
GROUP BY YEARWEEK(created_at)
返回
|yearweek|count|
================
| 201701 | 221 |
| 201702 | 253 |
| 201703 | 282 |
| 201704 | 252 |
| 201705 | 247 |
| 201706 | 135 |
我真正想要得到的是在某一周或前三周内活跃的用户数量。
换句话说,如果用户上周,或2周前或3周前处于活动状态,他也应该计算本周。 (总共4周)显然,用户也应该被计入他活跃的前几周。
是否可以使用MySql实现此目的?如果是这样,怎么样?
答案 0 :(得分:1)
可以使用4周的时间,例如:
select count(distinct acccount_id)
from activities
where created_at BETWEEN curdate( ) AND DATE_SUB(curdate(), INTERVAL 4 WEEK)
答案 1 :(得分:1)
您希望在一周内计算,即在该周或前三周中有一个活跃的用户。
一种简单的方法是相应地生成用户/周记录(即当用户在第3周活跃时,在第4周内构建假记录以假装用户也是活动的) ,#5和#6)。
select wk, count(*)
from
(
select account_id, yearweek(created_at) as wk from activities
union
select account_id, yearweek(created_at + interval 7 day) as wk from activities
union
select account_id, yearweek(created_at + interval 14 day) as wk from activities
union
select account_id, yearweek(created_at + interval 21 day) as wk from activities
) x
GROUP BY wk
ORDER BY wk;
(您也可以UNION ALL
使用COUNT(DISTINCT account_id)
代替UNION
和COUNT(*)
。)