2011-04-26 128 views
0

出現每週至少一次選擇的用戶假設你有一個簡單的表如下所示:幾個星期

+---------+---------------------+ 
| 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的周?

+1

由於這裏最需要的過濾器有些特定的數據庫,如果你能告訴我們你用什麼樣的(和版本)的SQL Server將是有益的。 – Wolph 2011-04-26 15:00:15

+1

好點。它是mysql – 2011-04-26 15:00:56

+0

「一週一次」對你意味着什麼?假設我在2011年4月12日星期二登錄,並於2011年4月21日星期四再次登錄。如果「周」意味着從週一到週日,我已經每週登錄一次,連續兩週。如果「周」意味着登錄之間的七天,我沒有。 – 2011-04-26 15:50:55

回答

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 
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;