pl / sql与上一行比较

时间:2012-06-14 00:08:29

标签: plsql oracle11g

目标是在具有相同ID的10分钟间隔内组合Time_a。 并将ID分组。

ID   Time_a        ->           ID    
------------                    ----------
1    12:10:00                   1
1    12:15:00                   2
1    12:20:00                   2
2    12:25:00
2    12:35:00
2    02:00:00

它变为两个'2',因为第5行和第6行之间的时间间隔超过10分钟。 我能够在10分钟内区分,但它不区分ID。

select ID    
from(
    select id, Time_a, min(time) OVER (order by id, time rows between 1 preceding and 1 preceding) prev_t_stamp
    from dual
)
where abs(Time_a-prev_t_stamp)>10/1440

1 个答案:

答案 0 :(得分:0)

如果time_a是date,那么它的工作原理如下。如果是时间戳,则需要将其转换为日期,否则它将无法正常工作。这是我的测试脚本

drop table test;
create table test (id number, time_a date);
insert into test values (1, to_date('12:10','HH24:MI'));
insert into test values (1, to_date('12:15','HH24:MI'));
insert into test values (1, to_date('12:20','HH24:MI'));
insert into test values (2, to_date('12:25','HH24:MI'));
insert into test values (2, to_date('12:35','HH24:MI'));
insert into test values (2, to_date('14:00','HH24:MI'));

select id from (
select distinct id, case from (
select ID,case when abs(Time_a-prev_t_stamp)>10/1440 then '>' end case
from(
    select id, Time_a, min(time_a) OVER (order by id, time_a rows between 1 preceding and 1 preceding) prev_t_stamp
    from test
)
)
) order by 1

这导致:

table TEST dropped.
table TEST created.
1 rows inserted.
1 rows inserted.
1 rows inserted.
1 rows inserted.
1 rows inserted.
1 rows inserted.

ID
--
 1 
 2 
 2