简体   繁体   English

间隔添加到日期

[英]Interval addition onto date

I'm going to attempt to explain the logic and hopefully someone can understand and help me. 我将尝试解释其逻辑,并希望有人能够理解和帮助我。

Effectively I'm looking for people within my database that have stopped transacting within the first 120 days of first creating their account, but have been inactive for 120 days since their last transaction. 实际上,我正在数据库中寻找那些在首次创建帐户后的前120天内已停止交易,但自上次交易以来120天内处于非活动状态的人员。

Basically if someone transacts for 120 days and then stops and 3 years later they transact again, I need them to fall into this list. 基本上,如果某人进行了120天的交易然后停了下来,而3年后又再次进行交易,我需要他们进入此列表。 So using max(transaction.created_at) isn't going to work. 因此,使用max(transaction.created_at)是行不通的。

Hopefully I've explained myself correctly. 希望我已经正确地解释了自己。

I assume you have a log of the type 我假设您有以下类型的日志

table transaction
    user; Timestamp

first step is sorting the correct sequence 第一步是对正确的顺序进行排序

select t.*, 
@curRow := @curRow + 1 AS row_number 
from transaction t 
JOIN  (SELECT @curRow := 0) r 
order by user, timestamp

result 结果

user, timestamp, row_id
1       t1           1
1       t1+x         2
...

next step is to join consecutive actions by the same user 下一步是加入同一用户的连续操作

select * from
    (select t.*, 
    @curRow := @curRow + 1 AS row_number 
    from transaction t 
    JOIN  (SELECT @curRow := 0) r 
    order by user, timestamp) a
inner join
    (select t.*, 
    @curRow := @curRow + 1 AS row_number 
    from transaction t 
    JOIN  (SELECT @curRow := 0) r 
    order by user, timestamp)b
on a.user=b.user and a.row_id=b.row_id-1

Result: 结果:

user timestamp row user timestamp row
 1      t1      1    1     t1+x    2
 2      t1+x    2    1    t1+x+x2  3
...

now you just need to filter by time span between events 现在您只需要按事件之间的时间间隔进行过滤

 select * from
        (select t.*, 
        @curRow := @curRow + 1 AS row_number 
        from transaction t 
        JOIN  (SELECT @curRow := 0) r 
        order by user, timestamp) a
    inner join
        (select t.*, 
        @curRow := @curRow + 1 AS row_number 
        from transaction t 
        JOIN  (SELECT @curRow := 0) r 
        order by user, timestamp)b
    on a.user=b.user and a.row_id=b.row_id+1
WHERE datediff(b.timestamp, a.timestamp)>120

now you have a lsit of users that had a break longer than 120 days between transactions if you need this to happen within first few days from creating an acc, just add where user in(select user from .... where datediff(min(timestamp, creation_Date)<120) or do an inner join on user_id to filter by that subquery 现在,如果您需要在创建acc的头几天内发生交易,那么用户之间的交易中断时间会超过120天,只需添加where user in(select user from .... where datediff(min(timestamp, creation_Date)<120)或对user_id进行内部联接以由该子查询过滤

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM