select 2nd row in Plsql

我与影子孤独终老i 提交于 2019-12-02 14:49:47

问题


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?

  1. I know how this is done using Oracle constructs like rownum or mysql constructs like limit, so I am not looking for those.

回答1:


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



回答2:


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)



来源:https://stackoverflow.com/questions/13700106/select-2nd-row-in-plsql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!