间隔添加到日期

时间:2013-10-08 08:28:21

标签: mysql postgresql date

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

有效地,我正在寻找我的数据库中的人员,他们在首次创建帐户的前120天内停止了交易,但自上次交易以来已经停用了120天。

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

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

1 个答案:

答案 0 :(得分: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

现在,您有一些用户在交易之间休息时间超过120天 如果您在创建acc后的前几天内需要这样做,只需添加where user in(select user from .... where datediff(min(timestamp, creation_Date)<120)或在user_id上执行内部联接以按子查询过滤