I have some data in the format of;
Client Amt Date
ABC Co £250 20/09/16
ABC Co £250 20/10/16
CDE Co £200 20/11/16
CDE Co £200 20/10/16
CDE Co £-200 20/09/16
FGH Co £600 01/01/16
FGH Co £-500 20/09/16
FGH Co £-50 20/10/16
FGH Co £100 20/11/16
I can pivot it like this easily;
Client Balance 0-29days 30-59days 60-89days 90days+
ABC Co £500 £0 £250 £250 £0
CDE Co £200 £200 £200 £-200 £0
FGH Co £100 £100 £-50 £-500 £600
IJK Co £-100 £100 £0 £0 £-200
But I need it to look like;
Client Balance 0-29days 30-59days 60-89days 90days+
ABC Co £500 £0 £250 £250 £0
CDE Co £200 £200 £0 £0 £0
FGH Co £100 £100 £0 £0 £50
IJK Co £-100 £0 £0 £0 £-100
The columns or "aging buckets" represent the age of a debit/credit. A single transaction will not occur in more than one bucket. If there are credits and debits they should be applied to eachother (starting with the oldest). So to elaborate on a few of the records...
CDE Co; The earliest transaction £-200 credit on 20/09 is balanced by the next transaction £200 debit on 20/10. This only leaves the £200 debit on 20/11 (hence the £200 debit in the 0-29days bucket).
FGH Co; The earliest transaction £600 debit on 01/01 is part paid by the 2 payments of £-500 (20/09) and £-50 (20/10) leaving £50 of debit in the 90days+ bucket and a more recent debit of £100 on 20/11 in the 0-29days bucket.
Is there a query/formula I can use to evaluate this? Or am I going to have to use a cursor?
Thanks