gpt4 book ai didi

sql - 如何在 Oracle SQL 中选择前 1 位并按日期排序?

转载 作者:行者123 更新时间:2023-12-03 15:52:49 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





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

(6 个回答)



How to use Oracle ORDER BY and ROWNUM correctly?

(5 个回答)


4年前关闭。




有明确答复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

这将选择任意选择的一条记录 ( 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;

关于sql - 如何在 Oracle SQL 中选择前 1 位并按日期排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44430702/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com