简体   繁体   中英

Using rownum in sub query on oracle 11

I have query like this.It is working properly on 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)

But I am using oracle 11.That query is not working on oracle 11.Therefore I changed my query like that

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

It gives missing right paranthesis

How can I solve this problem.Do you have any idea?Actually I use a variable instead on 10 number.

Syntax is a bit different - you need an extra subquery so it would need to be more like... where customerId IN (select * from (select custId from Orders where orderStatus = 'S' and orderCity = 'Amsterdam' and ORDER BY custId DESC) where rownum <=10)

You wouldn't need the extra subquery if you didn't have the order by clause

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

I would phrase this with exists and row_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() ranks orders by descending customer id in the subquery. Then, we filter on the first 10 rows, and use exists to filter the corresponding rows in the outer query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM