sorting data in oracle

纵然是瞬间 提交于 2021-01-28 11:47:01

问题


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

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