【问题标题】:Oracle db get the last row of every sequence [duplicate]Oracle db获取每个序列的最后一行[重复]
【发布时间】:2021-11-05 00:13:40
【问题描述】:

我有一个表 order_status

id order_no seq_no status
1 123 1 order received
2 123 2 order processing
3 456 1 order received
4 789 1 order received
5 789 2 order processing
6 789 3 order completed

我想获取每个 order_no 的 max seq_no 的状态。

即:

id order_no seq_no status
2 123 2 order processing
3 456 1 order received
6 789 3 order completed

我试过了:

select * from order_status where id IN 
(select id from order_status where max(seq_no) group by order_no)

但 oracle db 无法识别该语句。分组依据有错误。

请帮忙。谢谢。

【问题讨论】:

  • 根据您的示例数据,结果中第 1 行的结果应为 id 2。

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


【解决方案1】:

使用窗口函数确定每个 order_no 的每一行的 row_number,然后只选择最高的 (rn = 1)。我假设您的 seq_no 值对于每个订单都是唯一的,因此也可以使用 RANK

WITH sampledata(id,order_no,seq_no,status)
AS
(
SELECT 1,123,1,'order received' FROM DUAL UNION ALL
SELECT 2,123,2,'order processing' FROM DUAL UNION ALL
SELECT 3,456,1,'order received' FROM DUAL UNION ALL
SELECT 4,789,1,'order received' FROM DUAL UNION ALL
SELECT 5,789,2,'order processing' FROM DUAL UNION ALL
SELECT 6,789,3,'order completed' FROM DUAL
), sampledata_rn
AS
(
SELECT id,order_no,seq_no,status, 
       ROW_NUMBER() OVER (partition by order_no ORDER BY seq_no DESC) AS rn
  FROM sampledata
)
SELECT id,order_no,seq_no,status FROM sampledata_rn
WHERE rn = 1;

        ID   ORDER_NO     SEQ_NO STATUS          
---------- ---------- ---------- ----------------
         2        123          2 order processing
         3        456          1 order received  
         6        789          3 order completed 

【讨论】:

    猜你喜欢
    • 2011-05-26
    • 2019-05-06
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 2021-02-03
    • 2019-08-19
    • 2011-12-17
    • 2021-03-04
    相关资源
    最近更新 更多