-1

我想要一个 sql 2008 中的代码,它将添加下表的先前余额。喜欢

Balance= + Debit
Balance= -Credit



AccountReceivable
+----+------------+----------+----------+----------+---------+-------+--------+---------+-----+
| ID |  AR_Date   |  Ref_No  | Acc_Code | Acc_Name | Details | Debit | Credit |Balance |     |
+----+------------+----------+----------+----------+---------+-------+--------+---------+-----+
|  1 | 2013-04-10 |          |      101 | A/R      |  Kofi  | 500   | |   0   |      |
|  2 | 2013-04-10 |          |      101 | A/R      |  AMA   |0      | |   250 |      |
|  3 | 2013-04-11 | CH552778 |      101 | A/R      |  Boss  | 0     | |   50  |      |
+----+------------+----------+----------+----------+---------+-------+--------+---------+-----+
4

1 回答 1

0

将 CTE 与 ROW_NUMBER() 结合使用。在此之后,您可以查询 CTE 并将当前行号与前一个连接。

例如

;
WITH CTE as (
SELECT
    ac.*,
         RN = ROW_NUMBER() OVER (ORDER BY ID)
FROM
    AccountsReceivable ac

)

SELECT
cur.Balance + prev.Balance AS NewBalance
FROM
CTE cur 
LEFT OUTER JOIN CTE prev ON cur.RN = prev.RN + 1 
于 2013-04-10T12:15:50.050 回答