ORACLE SQL:选择时间差小于一分钟的记录

时间:2015-06-11 21:03:47

标签: sql oracle time difference

我有一张表,其中我有相同的记录但有不同的时间戳。 例如。 - 1

2015-03-03 13:41:11.0  [createService]: [accountNumber = 123456]
2015-03-02 01:19:11.0  [createService]: [accountNumber = 123456]
2015-03-02 01:19:06.0  [createService]: [accountNumber = 123456]

E.g。 - 2

2015-03-07 01:21:11.0  [createService]: [accountNumber = 567890]
2015-03-04 01:17:11.0  [createService]: [accountNumber = 567890]

我只需要在任何一天只提取超过2行且时差小于1分钟的记录。在上面的示例中,我应该只提取帐户123456,因为它在同一天有2条记录,时间差小于60秒。

这是用于拉取所有具有createservice行的记录多次但需要使用上述条件过滤列表的查询 -

SELECT acct_number
FROM CUSTOMER_LOG
WHERE LOG_EVENT LIKE '%createService%serviceName%'
AND LOG_EVENT_TMST > to_date('03/01/2015 00:00:00','MM/DD/YYYY HH24:MI:SS')
GROUP BY ACCT_NUMBER
having count(ACCT_NUMBER) > 1;

你能帮我解决一下可以在最快的时间内完成这项工作吗?提前谢谢!

2 个答案:

答案 0 :(得分:0)

使用lag()获取上一个时间戳。其余的只是基本的查询:

select acct_number, trunc(LOG_EVENT_TMST)
from (select cl.*, lag(log_event_tmst) over (partition by acct_number order by log_event_tmst) as prev_let
      from customer_log cl
      where LOG_EVENT_TMST > to_date('03/01/2015 00:00:00','MM/DD/YYYY HH24:MI:SS')
     ) cl
where (log_event_tmst - prevlet) < 1.0 / (60 * 24)
group by acct_number, trunc(LOG_EVENT_TMST);

答案 1 :(得分:0)

SELECT *
FROM   CUSTOMER_LOG c
WHERE  LOG_EVENT LIKE '%createService%serviceName%'
AND    LOG_EVENT_TMST > DATE '2015-01-03'
AND    EXISTS ( SELECT 'X'
                FROM   CUSTOMER_LOG x
                WHERE  c.LOG_EVENT   = x.LOG_EVENT
                AND    c.ACCT_NUMBER = x.ACCT_NUMBER
                AND    c.LOG_EVENT_TMST
                         BETWEEN x.LOG_EVENT_TMST - INTERVAL '1' MINUTE
                         AND     x.LOG_EVENT_TMST + INTERVAL '1' MINUTE
              );

SELECT *
FROM   CUSTOMER_LOG
WHERE  LOG_EVENT LIKE '%createService%serviceName%'
AND    LOG_EVENT_TMST > DATE '2015-01-03'
AND    (  LAG(  LOG_EVENT_TMST ) OVER ( PARTITION BY LOG_EVENT, ACCT_NUMBER ORDER BY LOG_EVENT_TMST )
             > LOG_EVENT_TMST - INTERVAL '1' MINUTE
       OR LEAD( LOG_EVENT_TMST ) OVER ( PARTITION BY LOG_EVENT, ACCT_NUMBER ORDER BY LOG_EVENT_TMST )
             < LOG_EVENT_TMST + INTERVAL '1' MINUTE
       );