How can I get just the first row in a result set AFTER ordering?

こ雲淡風輕ζ 提交于 2019-11-30 22:48:22

问题


This gives me just one row (the first one):

SELECT BLA
FROM BLA
WHERE BLA
AND ROWNUM < 2

However, I want the most recent date val; I can make that the first row this way:

SELECT BLA
FROM BLA
WHERE BLA
ORDER BY FINALDATE DESC

When I try to mix the two partial victories, though, it doesn't work - apparently the "Select the first row only" logic fires before the order by, and then the order by is subsequently ignored.


回答1:


This question is similar to How do I limit the number of rows returned by an Oracle query after ordering?.

It talks about how to implement a MySQL limit on an oracle database which judging by your tags and post is what you are using.

The relevant section is:

select *
from  
  ( select * 
  from emp 
  order by sal desc ) 
  where ROWNUM <= 5;



回答2:


In 12c, here's the new way:

select bla
  from bla
 where bla
 order by finaldate desc
 fetch first 1 rows only; 

How nice is that!




回答3:


You can nest your queries:

select * from (
    select bla
    from bla
    where bla
    order by finaldate desc
)
where rownum < 2



回答4:


An alternative way:

SELECT ...
FROM bla
WHERE finalDate = (SELECT MAX(finalDate) FROM bla) AND
      rownum = 1


来源:https://stackoverflow.com/questions/11978136/how-can-i-get-just-the-first-row-in-a-result-set-after-ordering

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