How to get the running balance from a table with a single SQL query

 

Table structure for Balance table-

 

Required result from the query -

 

Like in a Bank's money transaction output, the RunningBalance column is needed which displays the balance an account holds against that will account transaction.

 

 

Query to achieve it -

 

Explanation -

The result is achieved by a self join of the Balances table. The first table b1 returns the complete table output, inner join has two conditions. The first condition 'b1.DateStamp >= b2.DateStamp' is the most important which gives the result for SUM(b2.Amount). The last two records for BalanceID 4 and 6 have the exact same DateStamp hence without the second condition 'b1.BalanceID >= b2.BalanceID' will give same result for the RunningBalance column.

Comments

March 8. 2008 17:11

Devendra Deshmukh

Great start Adel.

Keep blogging.

Best regards,
Devendra Deshmukh

Devendra Deshmukh

June 10. 2008 07:04

Darryl Mekeel

This is a cool query works great however if I update any record say to do a cleared or reconciled value it throws the whole deal off anyway around this???

Darryl Mekeel

Comments are closed