[英]Get user who has transaction in last 7 days, and only one transaction in 30 days
我有一张如下表,今天是 2021-05-25。
用户身份 | 交易日期 |
---|---|
1 | 2021-05-21 |
1 | 2021-05-12 |
4 | 2021-05-25 |
1 | 2021-04-03 |
3 | 2021-05-15 |
3 | 2021-04-02 |
4 | 2021-03-25 |
我想要 output 是 4。
由于 1 次在 7 天内有交易,但 2 次在 30 天内交易。 3 7天内没有任何交易。 只有 4 个在 7 天内有交易,这是 30 天内唯一的交易。
我只能使用第一个条件过滤
WHERE t.TransactionDate > to_date('2021-05-17')
GROUP BY 1
谁能帮助如何应用这两种条件?
您可以使用having
以下功能的聚合:
select userid
from t
where transactiondate >= curdate() - interval 30 day
group by userid
having count(*) = 1 and
max(transactiondate) >= curdate() - interval 7 day;
如果您想要交易详细信息,则要复杂一些:
select t.*
from transactions t
where t.transactiondate >= curdate() - interval 7 day and
not exists (select 1
from transactions t2
where t2.userid = t.userid and
t2.transactiondate >= curdate() - interval 30 day and
t2.transactiondate <> t.transactiondate
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.