SQL 查询以获取 OrderID、transactionID、基于 Char 的交易状态的 Status

SQL query to fetch OrderID, transactionID, Status based on transaction status which is Char

我有下面的表格,我想在其中获得基于状态(Char)的最低交易条目。

表 1(顺序):

OrderID    Product
------------------
   1          A 
   2          B
   3          A

表 2(事务):

OrderID   TransactionID    Status
---------------------------------
   1           1           LOW
   1           2           HIGH
   1           3           MID
   2           4           MID
   2           5           HIGH
   3           6           LOW

如何获取状态最低的交易

OrderID    Status
-----------------
  1        LOW    
  2        MID    
  3        LOW

一种方法使用 row_number():

select t.*
from (select t.*,
             row_number() over (partition by orderid
                                order by instr('LOW,MEDIUM,HIGH', status) as seqnum
      from transaction t
     ) t
where seqnum = 1;

instr() 只是一种为字符串分配顺序的便捷方式。它returns状态在第一个参数中的位置,在这种情况下便于排序。