title: sql: sort rows using a running sum column
body: <p>I have a table which contains bank statements. In each row I have the date of the bank transaction, the amount, and the running balance (the balance after the processing the transaction).
  I also have the current balance, which equals the running balance of the last trx.</p>
  
  <p>The problem is that the transactions are not sorted according to posting order. I would like to sort them, using the information on each row and the following natural logic:</p>
  
  <p>After sorting, for each row, the running balance will be the 'starting balance' for the next row, where starting balance for a row = running balance - transaction amount. The rows need to be sorted by date also, of course.</p>
  
  <p>For example, say all transaction are posted on the same day. <br/>
  Running balance = 0<br/>
  <br/>
  Trx 1: amount  50, running balance -51<br/>
  Trx 2: amount 51, running balance 0<br/>
  Trx 3: amount 60, running balance -101.<br/></p>
  
  <p>So the order (from latest to first):<br/>
  Trx 2<br/>
  Trx 1<br/>
  Trx 3<br/></p>
  
  <p>It's possible that there will be several valid orders. In that case I would suffice for any valid ordering.</p>
  
  <p>Is this possible in SQL (any variant)? I though about doing this using self joins and partitions, but I'm bounded to making the number of joins equal to the maximal number of trxs posted in a single day, while I would like a solution for any number of trxs posted in a single day.</p>