【问题标题】:Select a record with most recent date and time in Oracle [duplicate]在Oracle中选择具有最近日期和时间的记录[重复]
【发布时间】:2017-09-14 11:08:15
【问题描述】:

我有一个关于 Oracle 中的 SQl 查询的问题,其中 IO 需要选择具有最新日期和时间的行,其中日期和时间被插入到两个单独的列中。

TransactionRecords

 CustomerID    TransactionDate   TransactionTime
-------------------------------------------------------
  0206016         17-APR-17         15:29:34
  0213570         17-APR-17         15:29:32
  0211384         17-APR-17         13:29:34
  0487674         16-APR-17         14:29:30
  0487759         15-APR-17         13:29:32
  0487213         12-APR-17         13:29:32
  0191022         11-APR-17         15:29:33
  1141158         29-OCT-16         01:25:51

我希望我的查询重新返回最近的交易,应该是:

   CustomerID    TransactionDate   TransactionTime
  ---------------------------------------------------
    0206016        17-APR-17            15:29:34

当我运行以下查询时:

 select * from TransactionRecords tst
 where tst.TransactionDate  in (select max(TransactionDate) from 
 TransactionRecords)

我正在获取最近日期发生的所有交易。 有人可以给我任何建议吗?

【问题讨论】:

  • 合并日期和时间列并将其转换为日期时间。然后按this的降序选择top 1的顺序。
  • 如何存储日期和时间变量?
  • 它们存储为 DATE 类型
  • @Ullas Oracle 没有 DATETIME 数据类型 - DATE 数据类型同时具有日期和时间组件。此外,在 Oracle 12c 之前,不支持 TOP 1 语法。
  • @MT0 :哦,对不起,我不知道。我的错。我只是根据我的 SQL Server 知识发表评论

标签: sql oracle greatest-n-per-group


【解决方案1】:

在 Oracle 12c 中,您可以这样做:

SELECT *
FROM   your_table
ORDER BY TransactionDate DESC, TransactionTime DESC
FETCH  FIRST 1 ROWS ONLY;

在较低版本中,您可以使用ROWNUM 伪列:

SELECT *
FROM   (
  SELECT *
  FROM   your_table
  ORDER BY TransactionDate DESC, TransactionTime DESC
)
WHERE  ROWNUM = 1;

【讨论】:

  • 我使用了以下查询,似乎可以正常工作: select * from TransactionRecords where (to_date(to_char(TransactionDate ,'dd-mon-yyyy') ||' '|| TransactionTime ,'dd-mon -yyyy hh24:mi:ss')) = (select max(to_date(to_char(TransactionDate ,'dd-mon-yyyy') ||' '|| TransactionTime ,'dd-mon-yyyy hh24:mi:ss') ) 来自 TransactionRecords)
【解决方案2】:

使用row_number()。我使用 CTE 来提高可见性,但子查询也可以使用

with CTE as
(
  select t1.*,
         row_number() over(order by TransactionDate desc, TransactionTime desc) as rn
  from MyTable t1
)
select CTE.*
from CTE
where rn = 1

【讨论】:

    【解决方案3】:

    从 TransactionRecords tst 中选择 * 按 tst.TransactionDate||tst.TransactionTime DESC 排序

    【讨论】:

    • DATE 数据类型上使用|| 字符串连接将在交易日期使用NLS_DATE_FORMAT 会话参数作为格式掩码隐式调用TO_CHAR() - 除非将其设置为ISO8601类型格式,这可能不会导致正确的排序(并且可能会被个别用户在不更改查询的情况下更改其会话参数而破坏)。
    猜你喜欢
    • 1970-01-01
    • 2013-08-25
    • 1970-01-01
    • 2018-07-19
    • 2013-04-11
    • 1970-01-01
    • 2018-04-20
    • 2021-07-21
    • 1970-01-01
    相关资源
    最近更新 更多