My requirement is to get each client's latest order, and then get top 100 records.
I wrote one query as below to get latest orders for each client. Internal query works fine. But I don't know how to get first 100 based on the results.
SELECT * FROM ( SELECT id, client_id, ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn FROM order ) WHERE rn=1
Any ideas? Thanks.
As Moneer Kamal said, you can do that simply: SELECT id, client_id FROM order WHERE rownum <= 100 ORDER BY create_time DESC; Notice that the ordering is done after getting the 100 row.
For example, TOP(10) would return the top 10 rows from the full result set. Optional. If PERCENT is specified, then the top rows are based on a percentage of the total result set (as specfied by the top_value).
To select first 10 elements from a database using SQL ORDER BY clause with LIMIT 10. Insert some records in the table using insert command. Display all records from the table using select statement. Here is the alternate query to select first 10 elements.
Assuming that create_time contains the time the order was created, and you want the 100 clients with the latest orders, you can:
create_time desc
ROWNUM
Query:
SELECT * FROM ( SELECT * FROM ( SELECT id, client_id, create_time, ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn FROM order ) WHERE rn=1 ORDER BY create_time desc ) WHERE rownum <= 100
UPDATE for Oracle 12c
With release 12.1, Oracle introduced "real" Top-N queries. Using the new FETCH FIRST...
syntax, you can also use:
SELECT * FROM ( SELECT id, client_id, create_time, ROW_NUMBER() OVER(PARTITION BY client_id ORDER BY create_time DESC) rn FROM order ) WHERE rn = 1 ORDER BY create_time desc FETCH FIRST 100 ROWS ONLY)
you should use rownum in oracle to do what you seek
where rownum <= 100
see also those answers to help you
limit in oracle
select top in oracle
select top in oracle 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With