预事务滚动平衡SQL Server 2008

时间:2015-05-15 07:23:48

标签: sql-server-2008 common-table-expression

我有几个相对简单的表格(下面的例子)。

其中有一个帐户详细信息:

AccountNo     | CurrentBalance*         | ReferredBalance
12345         | £1254.25                | 1500.00

当前余额每小时刷新一次,因此不是静态的

另一个人有付款:

Accountno     | TranasctionNo   | TransDate   | Amount |
123456        | 558745489       | 01/01/2015  | £25.99 |
123456        | 558745490       | 01/02/2015  | £25.99 |
123456        | 558745491       | 01/02/2015  | £25.99 |

我的任务是根据收到的付款(包括预交易金额)保持滚动余额。

例如,我需要输出镜像:

AccountNo | TransactionDate | PreTransactionBalance | Amount | Current Balance|
123456    | 01/01/2015      | 1254.25               | 25.99  | 1228.26|
123456    | 01/02/2015      | 1228.26               | 25.99  | 1202.27|
123456    | 01/03/2015      | 1202.27               | 25.99  | 1176.28|
123456    | 01/03/2015      | 1176.28               | -100   | 1276.28|

我添加了负数,因为它需要计算借方和贷方。

无法安排如何使滚动的预交易总数发挥作用。希望这很清楚!

1 个答案:

答案 0 :(得分:1)

您可以使用SUM(amount) OVER()根据amount滚动TransactionNo,然后根据此值计算事务前和当前余额。

示例数据

DECLARE @Account TABLE
(
AccountNo VARCHAR(10) ,
CurrentBalance MONEY,
ReferredBalance MONEY
)

DECLARE @AccountPayment TABLE
(
Accountno VARCHAR(10),TranasctionNo VARCHAR(10),TransDate DATE,Amount MONEY
)
insert into @Account VALUES
('12345','£1254.25','1500.00');

insert into @AccountPayment values
('12345','558745489','01/01/2015','£25.99'),
('12345','558745490','01/02/2015','£25.99'),
('12345','558745491','01/02/2015','£25.99'),
('12345','558745492','01/02/2015','-100');

<强>查询

SELECT AP.AccountNo,
    TransDate,
    A.CurrentBalance - SUM(amount) OVER(ORDER BY TranasctionNo) + amount as PreTransactionBalance ,
    amount,
    A.CurrentBalance - SUM(amount) OVER(ORDER BY TranasctionNo) Current_Balance
FROM @AccountPayment AP
INNER JOIN @Account A
ON AP.Accountno = A.Accountno

修改

SQL Server 2008 / SQL Server 2008 R2中的ORDER BY似乎不支持SUM() OVER()。根据{{​​3}}

  

ORDER BY Clause不能与聚合窗口函数一起使用。

我们可以像这样使用CROSS APPLY

SELECT AP.AccountNo,
    TransDate,
    A.CurrentBalance - pre_amount as PreTransactionBalance ,
    amount,
    A.CurrentBalance - pre_amount - amount Current_Balance
FROM @AccountPayment AP
INNER JOIN @Account A
ON AP.Accountno = A.Accountno
CROSS APPLY
(
     select ISNULL(sum(amount),0) as pre_amount 
     from @AccountPayment ap1 
     where ap1.Accountno = ap.Accountno and ap1.TranasctionNo < ap.TranasctionNo
 ) as b

<强>输出

AccountNo   TransDate   PreTransactionBalance   amount  Prev_Payments
12345   2015-01-01  1254.25 25.99   1228.26
12345   2015-01-02  1228.26 25.99   1202.27
12345   2015-01-02  1202.27 25.99   1176.28
12345   2015-01-02  1176.28 -100.00 1276.28

msdn