2

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.

4

1 回答 1

1

您正在寻找递归的东西 - 它考虑所有以前的事务并聚合它们,将它们与当前行进行比较。您需要有选择地将表连接到自身,计算每行截至当前日期的余额。您可以使用递归 CTE,也可以使用 T-SQL OVER 子句 - 请参阅http://msdn.microsoft.com/en-us/library/ms189461.aspx

于 2013-02-15T17:52:24.790 回答