0

I have a table which has data as:

enter image description here

My expected output is:

enter image description here

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
2
  • 1
    The query you posted is only guaranteed to return an arbitrary 2 rows-- any 2 rows would be equally valid. If you want to return a specific 2 rows, you'd need to tell us which rows you want to return. I have no idea how you determined that you wanted (3,300) and (2,600) to be returned rather than either of the other two rows. Commented Sep 30, 2019 at 15:31
  • Table data is considered unordered. It is left to chance which two rows you get with WHERE ROWNUM < 3. Commented Sep 30, 2019 at 15:34

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.