选择用户每周至少出现一次,持续数周

时间:2011-04-26 14:56:16

标签: mysql sql

假设你有一个如下的简单表:

+---------+---------------------+
| user_id | activity_date       |
+---------+---------------------+
|   23672 | 2011-04-26 14:53:02 |
|   15021 | 2011-04-26 14:52:20 |
|   15021 | 2011-04-26 14:52:09 |
|   15021 | 2011-04-26 14:51:51 |
|   15021 | 2011-04-26 14:51:38 |
|    6241 | 2011-04-26 14:51:12 |
|     168 | 2011-04-26 14:51:12 |
...

如何选择过去4周内每周至少出现一次的user_ids集合?

2 个答案:

答案 0 :(得分:4)

select user_id, 
sum(if(activity_date between now() - interval 1 week and now(),1,0)) as this_week,
sum(if(activity_date between now() - interval 2 week and now() - interval 1 week,1,0)) as last_week,
sum(if(activity_date between now() - interval 3 week and now() - interval 2 week,1,0)) as two_week_ago,
sum(if(activity_date between now() - interval 4 week and now() - interval 3 week,1,0)) as three_week_ago
from activities
where activity_date >= now() - interval 4 week 
group by user_id
having this_week > 0 and last_week > 0 and two_week_ago > 0 and three_week_ago > 0

答案 1 :(得分:0)

这使用了Oracle语法,因此MySql可能需要进行一些清理,但是如果在4周内每次发生活动,您可以使用一系列子查询从表中进行选择,然后按用户汇总总计,然后只选择有活动>的用户每周0次。

select user_id from 
{
  select user_id, SUM(in_week_0) sum_week_0,SUM(in_week_1) sum_week_1,SUM(in_week_2) sum_week_2,SUM(in_week_3) sum_week_3 from
  (
    select user_id, 
      activity_date, 
      CASE 
        WHEN activity_date < '01-MAY-11' AND activity_date >=  '24-APR-11' THEN 1
        ELSE 0
      END in_week_0,
      CASE 
        WHEN activity_date < '24-APR-11' AND activity_date >=  '17-APR-11' THEN 1
        ELSE 0
      END in_week_1,
      CASE 
        WHEN activity_date < '17-APR-11' AND activity_date >=  '10-APR-11' THEN 1
        ELSE 0
      END in_week_2,
      CASE 
        WHEN activity_date < '10-APR-11' AND activity_date >=  '03-APR-11' THEN 1
        ELSE 0
      END in_week_3
        from table
  )
  group by user_id
)
where sum_week_0 > 0 and sum_week_1 > 0 and sum_week_2 > 0 and sum_week_3 > 0;