Reputation: 8678
Lets say I have the following table:
SomeTable(
id,
price
)
How do I select the 2nd highest priced row from this table? Note : This has to be done in Pl/SQL, in a database agnostic way. Is it possible to do this without any loops?
rownum
or mysql constructs like limit
, so I am not looking for those.Upvotes: 0
Views: 1519
Reputation: 8678
Isn't this simple? God knows why I didn't think about it before!
select max(price) from tnum where price <> (select max(price) from tnum)
Upvotes: 1
Reputation: 8361
CREATE TABLE mytable (id NUMBER PRIMARY KEY, price NUMBER NOT NULL);
INSERT INTO mytable VALUES (1, 10);
INSERT INTO mytable VALUES (2, 20);
INSERT INTO mytable VALUES (3, 20);
INSERT INTO mytable VALUES (4, 30);
SELECT id, price
FROM (
SELECT id, price, RANK() OVER (ORDER BY price DESC) AS r
FROM mytable
)
WHERE r=2;
ID PRICE
--- -----
2 20
3 20
Upvotes: 1