【问题标题】:Oracle SQL How to select records that have the latest dateOracle SQL 如何选择具有最新日期的记录
【发布时间】:2023-01-13 15:05:26
【问题描述】:

我需要从 Y 列中提取一条记录,其中日期列中有最后一个日期

例子

id Y DATE
a 1 2020
a 2 2021
a 2 2022
b 1 1999
b 1 2015
c 3 2001
c 3 2004
c 7 2010

【问题讨论】:

  • “我需要”是毫无疑问的。您没有告诉我们您尝试过什么以及什么没有按预期工作。这个示例数据是否已经是应该涵盖的整个用例?这甚至不需要任何子查询或其他“复杂”的东西,但可以用简单的 MAX 和 GROUP BY 来完成。

标签: sql oracle


【解决方案1】:

一种选择是按年份降序排列每个 id 的行,然后获取排名最高的行。

样本数据:

SQL> with
  2  test (id, y, datum) as
  3    (select 'a', 1, 2020 from dual union all
  4     select 'a', 2, 2021 from dual union all
  5     select 'a', 2, 2022 from dual union all
  6     select 'b', 1, 1999 from dual union all
  7     select 'b', 1, 2015 from dual union all
  8     select 'c', 3, 2001 from dual union all
  9     select 'c', 3, 2004 from dual union all
 10     select 'c', 7, 2010 from dual
 11    ),

询问:

 12  temp as
 13    (select id, y, datum,
 14       rank() over (partition by id order by datum desc) rnk
 15     from test
 16    )
 17  select id, y, datum
 18  from temp
 19  where rnk = 1;

ID          Y      DATUM
-- ---------- ----------
a           2       2022
b           1       2015
c           7       2010

SQL>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-22
    • 2018-06-24
    • 2013-08-25
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多