2013-07-23 161 views
-1

我有此表下面的Oracle SQL條件選擇查詢

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的字段以遞增的順序。邏輯是time_type'1'需要與同一個rid的下一個time_type'2'配對。如果time_type'1'或'2'出現在由date_time排序的2個或更多的組中,我將採用較早的一個並忽略其餘部分。

可以這樣做嗎?

+0

這標記MySQL和Oracle。你在用哪個? –

回答

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