查询同标题的最新id

Queries for the latest id with the same titles

我是 Oracle 的新手 SQL。由于我已经开始自己学习数据库查询编程,因此我正在寻找解决问题的技巧或解决方案:

我为自己创建了一个随机数据库,其中包含不同产品的订单。在我的高级订单 table 中,我详细列出了在任何给定时间更改的内容。

下面我介绍一下情况:

enter image description here

我想构建数据库查询,以便它仅搜索给定组中 ID 最旧的记录:

enter image description here

得到这样的东西:

enter image description here

我试过这个查询:

SELECT *
FROM database.advancedorders
INNER JOIN (
  SELECT
    TICKET_ID,
    max(id) as maxId
    from database.advancedorders
    group by TICKET_ID
) groupedTable
ON advancedorders.id = groupedTable.maxId
and advancedorders.TICKET_ID = groupedTable.TICKET_ID

但是,我没有收到此查询...有人可以告诉我吗?

这是一种选择;阅读代码中的注释(第 1 - 16 行中的示例数据,因此您可能感兴趣的查询从第 17 行开始):

SQL> with test (id, ticket_id, title) as
  2    (select 1, 2345009, 'Banana' from dual union all
  3     select 2, 2345009, 'Banana' from dual union all
  4     select 3, 2345009, 'Apple' from dual union all
  5     select 4, 2345009, 'Apple' from dual union all
  6     --
  7     select 5, 4535003, 'Lemon' from dual union all
  8     select 5, 4535003, 'Lemon' from dual union all
  9     select 6, 4535003, 'Lemon' from dual union all
 10     --
 11     select 7, 3350001, 'Pear' from dual union all
 12     select 8, 3350001, 'Pear' from dual union all
 13     select 9, 3350001, null from dual union all
 14     --
 15     select 10, 4429005, 'Watermelon' from dual
 16    ),

 17  temp as
 18    -- rank them in descending order
 19    (select id, ticket_id, title,
 20       row_number() over (partition by ticket_id order by id desc) rn
 21     from test
 22    )
 23  -- finally, return those that ranked the "highest" (rn = 1)
 24  select id, ticket_id, title
 25  from temp
 26  where rn = 1;

        ID  TICKET_ID TITLE
---------- ---------- ----------
         4    2345009 Apple
         9    3350001
        10    4429005 Watermelon
         6    4535003 Lemon

SQL>