Second highest value from Oracle DB's table [duplicate]

て烟熏妆下的殇ゞ 提交于 2021-02-10 03:06:22

问题


According to the tables:

USERS (user_name, email, balance)

How can I create a query that return the second highest user balance in the most efficient way ?

I successes to get this record (but not by the efficient way) with the query:

SELECT 
  * 
FROM  
  (SELECT 
    us.*,
    ROWNUM row_num
  FROM  
    (SELECT 
      u.*
    FROM
      users u
    ORDER BY
      u.BALANCE DESC) us
  WHERE
    ROWNUM < 3)
WHERE
  row_num > 1;

回答1:


I would use a window function:

select *
from (
  select u.*, dense_rank() over (order by balance desc) as rnk
  from users u
) t
where rnk = 2;

I don't think there will be a big performance difference to your query (especially not with an index on balance) but in my opinion it's easier to read and maintain.




回答2:


Try this:

SELECT * 
FROM (SELECT *   
      FROM USERS   
      ORDER BY balance DESC  
      FETCH FIRST 2 ROWS ONLY
      ) 
ORDER BY balance DESC  
FETCH FIRST 1 ROWS ONLY



回答3:


This should work even in case of more than one user having same 2nd largest balance..

select * from USERS where balance IN
  (select max(balance) 
     from (select balance from USERS 
    where balance NOT IN (select max(balance) from USERS))
);


来源:https://stackoverflow.com/questions/39100008/second-highest-value-from-oracle-dbs-table

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