选择时间差小于单列2小时的行

时间:2015-04-04 12:23:38

标签: sql oracle

表:TEST

Table : TEST

选择当天时间差小于2小时的行(按日期分组)。

这里输出应该是前两行,因为前两行的时差(18-JAN-15 01.08.40.000000000 PM-18-JAN-15 11.21.28.000000000 AM< 2小时)

NB: compare rows of same date.

输出:

Output

  CREATE TABLE TEST
  ( "ID" VARCHAR2(20 BYTE), 
    "CAM_TIME" TIMESTAMP (6)
  ) 

Insert into TEST (ID,CAM_TIME) values ('1',to_timestamp('18-JAN-15 11.21.28.000000000 AM','DD-MON-RR HH.MI.SSXFF AM'));
Insert into TEST (ID,CAM_TIME) values ('2',to_timestamp('18-JAN-15 01.08.40.000000000 PM','DD-MON-RR HH.MI.SSXFF AM'));

Insert into TEST (ID,CAM_TIME) values ('3',to_timestamp('23-JAN-15 09.18.40.000000000 AM','DD-MON-RR HH.MI.SSXFF AM'));
Insert into TEST (ID,CAM_TIME) values ('4',to_timestamp('23-JAN-15 04.22.22.000000000 PM','DD-MON-RR HH.MI.SSXFF AM'));

3 个答案:

答案 0 :(得分:4)

我采用了稍微不同的方法并使用LAG()LEAD()分析函数:

WITH mydata AS (
  SELECT 1 AS id, timestamp '2015-01-15 11:21:28.000' AS cam_time
    FROM dual
   UNION ALL
  SELECT 2 AS id, timestamp '2015-01-15 13:08:40.000' AS cam_time
    FROM dual
   UNION ALL
  SELECT 3 AS id, timestamp '2015-01-23 09:18:40.000' AS cam_time
    FROM dual
   UNION ALL
  SELECT 4 AS id, timestamp '2015-01-23 16:22:22.000' AS cam_time
    FROM dual
)
SELECT id, cam_time FROM (
    SELECT id, cam_time
         , LAG(cam_time) OVER ( PARTITION BY TRUNC(cam_time) ORDER BY cam_time ) AS lag_time
         , LEAD(cam_time) OVER ( PARTITION BY TRUNC(cam_time) ORDER BY cam_time ) AS lead_time
      FROM mydata
) WHERE CAST(lead_time AS DATE) - CAST(cam_time AS DATE) < 1/12
     OR CAST(cam_time AS DATE) - CAST(lag_time AS DATE) < 1/12

答案 1 :(得分:3)

此自连接查询可以完成工作:

SQL Fiddle

select distinct t1.id, t1.cam_time 
  from test t1 join test t2 on t1.rowid <> t2.rowid  
    and trunc(t1.cam_time) = trunc(t2.cam_time)
  where abs(t1.cam_time-t2.cam_time) <= 2/24
  order by t1.id

编辑:

如果cam_time是time_stamp类型,则条件应为:

where t1.cam_time between t2.cam_time - interval '2' Hour 
                      and t2.cam_time + interval '2' Hour

答案 2 :(得分:2)

这应该这样做。使用“存在”,您可以检查子查询是否返回任何结果。在这种情况下,子查询返回符合2个条件的行:

  1. 它们具有相同的日期(trunc(CAM_TIME)仅返回日期,然后进行比较)。
  2. 他们的时差少于两个小时。您可以减去两次以获得天数差异。将该差值乘以24,即可得到小时数。
  3. 结果:

    select
      t1.*
    from 
      TEST t1
    where
      exists
        ( select 'x' 
          from   TEST t2 
          where  t1.id <> t2.id                                -- Not the same row
                 trunc(t2.CAM_TIME) = trunc(t1.CAM_TIME)       -- Same date
                 and abs(t1.CAM_TIME - t2.CAM_TIME) * 24 < 2   -- < 2 hours