1

我将尝试解释逻辑,希望有人能理解并帮助我。

实际上,我正在我的数据库中寻找在首次创建帐户后的前 120 天内停止交易但自上次交易后 120 天内不活动的人。

基本上,如果有人交易 120 天然后停止交易,3 年后他们再次交易,我需要他们进入这个列表。所以使用max(transaction.created_at)是行不通的。

希望我已经正确解释了自己。

4

1 回答 1

1

我假设你有一个类型的日志

table transaction
    user; Timestamp

第一步是排序正确的序列

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

结果

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

下一步是加入同一用户的连续动作

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

结果:

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

现在您只需要按事件之间的时间跨度进行过滤

 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

现在,如果您需要在创建 acc 后的头几天内发生这种情况,那么您有一个 lsit 的用户在交易之间的休息时间超过 120 天,只需where user in(select user from .... where datediff(min(timestamp, creation_Date)<120)在 user_id 上添加或执行内部联接以按该子查询进行过滤

于 2013-10-08T09:02:08.733 回答