2015-10-28 40 views
1

例如,我有兩列。 AVarchar2Bdate列。如果另一列爲空,Oracle選擇最新記錄

數據樣本:

A   B 
---------- ----------- 
10/27/15  
10/28/15  Y 

我怎樣寫一個sql將檢查max(A)記錄,如果BNULL,如果它是那麼只有選擇它。所以在這種情況下,不應該返回行。

我希望這是有道理的。

回答

1

這裏有一個方法:

select s.* 
from (select s.* 
     from (select s.* 
      from sample s 
      order by a desc 
      ) s 
     where rownum = 1 
    ) s 
where s.B is null; 

這是Oracle稍微簡單12+:

select s.* 
from (select s.* 
     from sample s 
     order by a desc 
     fetch first 1 row only 
    ) s 
where s.B is null; 

另一種使用條件彙總:

select max(a) 
from sample 
having max(a) = max(case when b is null then a end); 
+0

所以,你的第一和第三種方法是最快的? – user3224907

+0

如果我有另一列,'C',它是PK,我可以使用row_number窗口函數,並按'B'降序排列? – user3224907

+0

如果你有一個'sample(a)'的索引,那麼前兩個應該比第三個快。 –