zulfi007
zulfi007

Reputation: 93

Finding aging of customer invoice in a ledger. No posting of credit against invoice number

I want to calculate bill aging days using SQl Server. When a bill is cleared, calculate its age.

Date     Invoice#   type   age     Debit   Credit   Balance
01/01              opening  27                      8061
01/01              Cr                      2000     6961
5/01               Cr                      5000     1961
5/1        5       Dr       30     3000             4961
27/1               Cr                      2000     2961
5/2                Cr                      2961        0

The opening balance gets cleared on 27 Jan; so, invoice age is 27 days. And, invoice # 5 is cleared on 5/2; so, its age will be 30 days. How do I do this in SQL Server code?

I have this cledger table in a SQL table.

I could not figure out how to do this recursive task of... selecting bill# and sum all credit till the debit amount is greater than the sum of credit. Using date of that credit transaction, calculate the difference in days between debit bill date and when this bill is cleared.

Any help will be appreciable. Thanks in advance.

Upvotes: 2

Views: 519

Answers (1)

David T. Macknet
David T. Macknet

Reputation: 3172

You're looking for something which is recursive - which considers all previous transactions & aggregates them, comparing them to the current row. You'll need to join the table to itself, selectively, calculating the balance as of the current date for each row. You could use a recursive CTE, or you could use the T-SQL OVER clause - see http://msdn.microsoft.com/en-us/library/ms189461.aspx .

Upvotes: 1

Related Questions