Reputation: 923
I have a table which has data as:
My expected output is:
I got my expected output as using rownum:
SELECT ID,PRICE FROM OT.TEST1 WHERE ROWNUM<3;
It's working finesince i have inserted the data serially as the output is coming with rownum ,but what,if the data were inserted as random below,my rownum will not work.Is there any new method?
ID PRice
3 300
3 600
8 600
2 600
Upvotes: 0
Views: 28
Reputation: 521028
You could use ROW_NUMBER()
here:
WITH cte AS (
SELECT t.*, ROW_NUMBER() OVER (ORDER BY PRICE, ID) rn
FROM OT.TEST1 t
)
SELECT ID, PRICE
FROM cte
WHERE rn <= 2;
Here we are assigning a row number over the entire table ordered first by price ascending, and then by ID
. Since three records are tied for a price of 600, the record with the lowest ID
would happen to be returned here.
Upvotes: 1