问题
I have a tricky scenario.
Data in the table is as follows
CustomerId Transaction Type Transaction Amount
1 Payment 100
1 payment 200
1 ReversePayment -100
1 ReversePayment -200
I have transnational table with transaction types being "Payment", "ReversePayment". There are multiple records for a customer with some records being Payment and some being ReversePayment.
Is there a way to sort data as follows
CustomerId Transaction Type Transaction Amount
1 Payment 100
1 ReversePayment -100
1 payment 200
1 ReversePayment -200
If any one have a solution, please help.
回答1:
For this dataset, this should do it:
order by
customerId,
abs(transaction_amount),
transaction_amount desc
This sort does not worry about the transaction type, but only about the amounts. The criteria on the absolute value of the amount ties records that have opposite values, then the next criteria puts the positive value first.
回答2:
The question is unclear, but my interpretation is that the OP wants to interleave the payments and reverses. This suggests window functions:
order by customerid,
abs(transactionamount),
row_number() over (partition by customerid, transactiontype, abs(transactionamout) order by customerid),
transactiontype asc
来源:https://stackoverflow.com/questions/60216700/sorting-data-in-oracle