如何使用sql中的时间戳找到相隔不到10分钟的事务

时间:2014-09-10 11:01:06

标签: sql oracle

我走了这么远:

select timestamp, trans, Count(trans)  
From(
    Select to_char(CREATED_TIMESTAMP) as timestamp,SOURCE_MSISDN||DEST_MSISDN||AMOUNT as trans
    From ADMDBMC.TRANSACTION_CASH
    WHERE TO_date(CREATED_TIMESTAMP) > = '1-sep-2014' AND TO_date(CREATED_TIMESTAMP) < '2-sep-2014'
    and STATUS_DESCRIPTION='SUCCESS'
    ) 

group by timestamp,trans
Having count(trans)>1
order by count(trans) desc

3 个答案:

答案 0 :(得分:0)

我认为您可以通过在最接近的10分钟内截取时间戳来实现这一目标:您可以将to_char(CREATED_TIMESTAMP) as timestamp替换为regexp_replace(to_char(CREATED_TIMESTAMP, 'dd-Mon-yyyy hh24:mi'), '.$', '0'),我认为您的分组将会正常。

编辑:之前的解决方案仅在2个交易属于10分钟相同倍数的一部分时才有效。这是一个更好的:

Select *
From
(
    Select CREATED_TIMESTAMP,
           SOURCE_MSISDN||DEST_MSISDN||AMOUNT as trans,
           lag(CREATED_TIMESTAMP, 1, null) over (partition by SOURCE_MSISDN||DEST_MSISDN||AMOUNT order by CREATED_TIMESTAMP) as PREVIOUS_TIMESTAMP
    From ADMDBMC.TRANSACTION_CASH
    Where TO_date(CREATED_TIMESTAMP) >= '1-sep-2014'
      And TO_date(CREATED_TIMESTAMP) < '2-sep-2014'
      And STATUS_DESCRIPTION='SUCCESS'
) 
where CREATED_TIMESTAMP <= PREVIOUS_TIMESTAMP + INTERVAL '10' MINUTE

lag分析函数允许为每一行获取由SOURCE_MSISDN / DEST_MSISDN / AMOUNT的串联标识的同一组的前一行的时间戳。然后,一旦我们有这个,我们只需要检查差异。

答案 1 :(得分:0)

Emmanuels方式将返回假阴性,例如,如果一次交易发生在11:49,第二次发生在11:52

您可以使用带窗口选项的LEAD或LAG聚合函数来获取较旧行的时间戳,然后计算当前值并计算difference between two timestamps 或带窗口的COUNT(*),例如:

select * FROM ( Select to_char(CREATED_TIMESTAMP) as timestamp,SOURCE_MSISDN||DEST_MSISDN||AMOUNT as trans ,COUNT(*) OVER (PARTITION BY SOURCE_MSISDN||DEST_MSISDN||AMOUNT ORDER BY CREATED_TIMESTAMP RANGE NUMTODSINTERVAL(600,'SECOND') PRECEDING) L_OF_TRANS From ADMDBMC.TRANSACTION_CASH WHERE TO_date(CREATED_TIMESTAMP) > = '1-sep-2014' AND TO_date(CREATED_TIMESTAMP) < '2-sep-2014' and STATUS_DESCRIPTION='SUCCESS' ) WHERE L_OF_TRANS > 1

答案 2 :(得分:0)

您应该尝试使用to_dsinterval功能。减去时间戳会给出间隔,因此您可以使用to_dsinterval比较时间戳。例如:

select *
from my_table x
where x.timestamp1 - x.timestamp2 < to_dsinterval ('00 00:10:00');

在此示例中,timestamp1将是更新的时间戳。