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

一曲冷凌霜 提交于 2019-12-08 11:45:07

问题


I have below tables where I want to get lowest transaction entry based on Status which is Char.

Table1 (Order):

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

Table2 (Transaction):

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

How can I get transaction with the lowest status

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

回答1:


One method uses 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() is just a convenient way to assign an ordering to strings. It returns the position of the status in the first argument, which is convenient for sorting purposes in this case.



来源:https://stackoverflow.com/questions/42096084/sql-query-to-fetch-orderid-transactionid-status-based-on-transaction-status-wh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!