0

当我组合查询包含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 功能。

希望你能对这个奇怪的问题有所了解。

4

1 回答 1

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
于 2012-11-27T10:40:45.947 回答