Oracle SQL条件选择查询

时间:2013-07-23 23:19:08

标签: sql oracle select plsql

我有下表

uid    rid   time_type    date_time

a11    1     2            5/4/2013 00:32:00 (row1)
a43    1     1            5/4/2013 00:32:01 (row2)
a68    1     1            5/4/2013 00:32:02 (row3)
a98    1     2            5/4/2013 00:32:03 (row4)
a45    1     2            5/4/2013 00:32:04 (row5)
a94    1     1            5/4/2013 00:32:05 (row6)
a35    1     2            5/4/2013 00:32:07 (row7)
a33    1     2            5/4/2013 00:32:08 (row8)

我可以使用普通的选择查询来提取数据,使其成为

uid    rid   time_type    date_time

a43    1     1            5/4/2013 00:32:01 (row2)
a98    1     2            5/4/2013 00:32:03 (row4)
a94    1     1            5/4/2013 00:32:05 (row6)
a35    1     2            5/4/2013 00:32:07 (row7)

date_time字段按asc顺序排列。逻辑是time_type'1'需要与同一rid的下一个time_type'2'配对。如果time_type'1'或'2'出现在由date_time排序的2个或更多的组中,我将采用较早的一个而忽略其余的。

可以这样做吗?

1 个答案:

答案 0 :(得分:0)

尝试此查询:

with src as (
  select tst.*,  
         case when time_type <> lag( time_type) over ( partition by rid order by date_time, time_type ) 
            then 1 else 0
         end take_me
  from tst
) 
select * from src where take_me = 1
order by rid, date_time;

这是SQL Fiddle demo