【问题标题】:查询具有相同标题的最新 id [重复]
【发布时间】:2021-12-29 16:42:11
【问题描述】:

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

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

下面我介绍一下情况:

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

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

【问题讨论】:

  • 错误是什么?还是输出你回来了?

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


【解决方案1】:

这是一种选择;在代码中读取 cmets(示例数据在第 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 2020-03-31
    • 2016-10-24
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    相关资源
    最近更新 更多