在 oracle 11 的子查询中使用 rownum

Using rownum in sub query on oracle 11

我有类似 this.It 的查询在 Oracle 12 上正常工作。

select * from customers where customerId IN (select custId from Orders where 
   orderStatus = 'S' and orderCity = 'Amsterdam' and ORDER BY custId DESC FETCH FIRST 10 ROWS ONLY)

但我正在使用 oracle 11.That 查询在 oracle 上不起作用 11.Therefore 我这样更改了我的查询

select * from customers where customerId IN (select custId from Orders where 
  orderStatus = 'S' and orderCity = 'Amsterdam' and ORDER BY custId DESC rownum <= 10)

给出missing right paranthesis

我该如何解决这个问题problem.Do你有什么想法吗?实际上我在 10 号上使用了一个变量。

语法有点不同 - 你需要一个额外的子查询,所以它需要更像...... where customerId IN (select * from (select custId from Orders where orderStatus = 'S' and orderCity = 'Amsterdam' and ORDER BY custId DESC) where rownum <=10)

如果没有 order by 子句就不需要额外的子查询

参考 https://docs.oracle.com/cd/B19306_01/server.102/b14200/pseudocolumns009.htm#:~:text=For%20each%20row%20returned%20by,has%202%2C%20and%20so%20on

我会用 existsrow_number() 来表达:

select c.* 
from customers 
where exists (
    select 1
    from (
        select custId, row_number() over(order by custid desc) rn
        from orders 
        where orderStatus = 'S' and orderCity = 'Amsterdam'
    ) o
    where o.rn <= 10 and o.cusid = c.customerid
)

row_number() 在子查询中按客户 ID 降序排列订单。然后,我们过滤前10行,并使用exists过滤外部查询中的相应行。