如何在Oracle SQL中选择前1和按日期排序?

时间:2017-06-08 08:39:08

标签: sql oracle

答案明确how to select top 1

select * from table_name where rownum = 1

以及如何按日期按降序排序:

select * from table_name order by trans_date desc

但它们不起作用(rownum未根据trans_date生成):

... where rownum = 1 order by trans_date desc

问题是如何选择按日期排序的前1名?

4 个答案:

答案 0 :(得分:17)

... where rownum = 1 order by trans_date desc

这将选择一个任意选择的记录(where rownum = 1),然后对此一条记录(order by trans_date desc)进行排序。

如Ivan所示,您可以使用子查询来订购记录,然后在外部查询中保留第一条记录where rownum = 1。但是,这非常特定于Oracle,并且违反了SQL标准,其中子查询结果被认为是无序的(即DBMS可以忽略order by子句)。

最好采用标准解决方案。从Oracle 12c开始:

select * 
from table_name 
order by trans_date desc
fetch first 1 row only;

旧版本:

select *
from
(
  select t.*, row_number() over (order by trans_date desc) as rn
  from table_name t
)
where rn = 1;

答案 1 :(得分:1)

您可以使用窗口函数:

Select
a.Actor_name,
b.Movies_name,
c.Revenue_generated
from
Table1 a
inner join Table2 b on a.Movies_ID = b.Movies_ID
inner join Table3 c on b.Movies_ID = c.Movies_ID
where c.Revenue_generated > 100 AND a.Actor_Name= 'A1'

另一种选择是加入派生表

select t.*
from (
  select *, 
         min(trans_date) over () as min_date,
         max(trans_date) over () as max_date
  from the_table 
) t 
where trans_date = min_date 
   or trans_date = max_date;

不确定哪一个更快,您需要检查执行计划

答案 2 :(得分:1)

现代Oracle版本有FETCH FIRST

select * from table_name order by trans_date desc
fetch first 1 row only

答案 3 :(得分:0)

应该有子查询,因此组合rownum & order可以起作用:

select * from (select * from table_name order by trans_date desc) AS tb where rownum = 1