加入收藏 | 设为首页 | 会员中心 | 我要投稿 核心网 (https://www.hxwgxz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长百科 > 正文

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

发布时间:2020-12-31 03:06:15 所属栏目:站长百科 来源:网络整理
导读:参见英文答案 How do I do top 1 in Oracle?????????????????????????????????????9个 ???????????? How do I limit the number of rows returned by an Oracle query after ordering?????????????????????????????????????14个 ???????????? Oracle SELECT

参见英文答案 > How do I do top 1 in Oracle?????????????????????????????????????9个
>???????????? How do I limit the number of rows returned by an Oracle query after ordering?????????????????????????????????????14个
>???????????? Oracle SELECT TOP 10 records????????????????????????????????????5个
>???????????? How to use Oracle ORDER BY and ROWNUM correctly?????????????????????????????????????5个
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名?

解决方法

... where rownum = 1 order by trans_date desc

这将选择一个任意选择的记录(其中rownum = 1),然后对这一个记录进行排序(按trans_date desc排序).

如Ivan所示,您可以使用子查询来订购记录,然后保留第一条记录,其中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;

(编辑:核心网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读