我需要一种有效的方式(如果可能的话)给我一个用户列表,每个月至少登录一次。
该表称为登录。 ID是user_id。
我需要一个在过去36个月内每月至少登录一次的用户列表! 我可以像这样做一长串嵌套子查询;
$response->exception->getStackTrace();
我正在使用Amazon redshift
由于
答案 0 :(得分:4)
这个逻辑应该有效:每个用户/月组合获得一行并计算这些行:
select user_id
from
( select user_id --one row per user/month
from login
-- the last 36 months
where timestamp >= timestamp '2015-02-01 00:00:00'
group by
user_id
,extract (year from timestamp::date)
,extract (month from timestamp::date)
) as dt
group by user_id
having count(*) = 36 -- one row per month
或者使用Redshift函数将时间戳截断为月份的第1个,然后是COUNT(DISTINCT):
select user_id
from login
where timestamp >= add_months(trunc('month', current_date),-35)
group by user_id
having count(distinct date_trunc('month', timestamp)) = 36