2012-11-27 35 views
0

當我將包含DENSE_RANK()的查詢合併爲IN子句的輸入時,我遇到了一些奇怪的結果。與DENSE_RANK和IN的奇怪行爲

爲了證明我把它們分開了;

此查詢

select * 
from ALL_QUOTE 
where ID in ('G002WMLS') 

返回1個結果:

ID  LongID StartDate EndDate 
G002WMLS 67888 01/10/2011 30/11/2011 

此查詢

select ID 
from (

select LongId, ID, DENSE_RANK() over (partition by LongId order by end_date desc, substr(ID, 2, 7) desc, start_date desc) d 
from WithoutPD 
) 

where d = 1 and LongId = '67888' 

也返回1個結果:

ID 
G002WMLS 

但是當我結合在一起他們兩個:

select * 
from ALL_QUOTE 
where ID in (

select ID 
from (

select LongId, ID, DENSE_RANK() over (partition by LongId order by end_date desc, substr(ID, 2, 7) desc, start_date desc) d 
from WithoutPD 
) 

where d = 1 

) 
and LongId = '67888'; 

我結束了兩個結果:

ID  LongID StartDate EndDate 
G002MIMQ 67888 01/10/2010 30/09/2011 
G002WMLS 67888 01/10/2011 30/11/2011 

我簡直不明白如何G002MIMQ被包含在結果中。我使用的是Oracle 11.2.0.1.0,但是我知道這可能是我誤解的通用SQL功能。

希望你能對這個奇怪的問題有所瞭解。

回答

1

您已將and LongID='67888'移至子查詢的where子句之外。

嘗試此查詢,而不是...

select * 
from ALL_QUOTE 
where ID in ( 
    select ID 
    from (  
     select LongId, ID, DENSE_RANK() over (partition by LongId order by end_date desc, substr(ID, 2, 7) desc, start_date desc) d 
     from WithoutPD   
    )   
    where d = 1 
    and LongId = '67888' 
); 

編輯

select 
    AllQuote.* 
from 
    AllQuote 
     inner join 
    (
     select ID 
     from (
      select LongId, ID, DENSE_RANK() over (partition by LongId order by end_date desc, substring(ID, 2, 7) desc, start_date desc) d 
      from WithoutPD 
     ) t 
     where d = 1 
     and LongId = '67888' 
    ) v 
     on AllQuote.ID = v.ID 
+0

我原本以爲是問題太多,但我提取從該條款的所有結果,並使用Excel中只檢查' G002WMLS'存在於結果中。 –

+0

數據集中是否有空值?如果用聯接替換子查詢中的'in'(請參閱上面的編輯),則查詢是否可以工作 – podiluska

+0

沒有空ID,如果我在子查詢中加入IN,我會得到兩個結果一樣)。 –