问题
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