计算SQL Server中贷款帐户的运行余额

时间:2017-08-23 07:17:42

标签: sql-server

这些表位于SQL Server中。我需要根据客户支付的金额获得每笔交易账户的未结余额。 PAYMENT表包含每笔交易中客户的付款。 Account表包含客户的帐户详细信息和贷款总额。

付款

    +--------------+------------+----------+
    | payment_date | account_no |  amount  |
    +--------------+------------+----------+
    | 2017-08-10   |  123456789 |   5000   |
    | 2017-08-15   |  987654321 |   3000   |
    | 2017-09-15   |  987654321 |   3000   |
    | 2017-10-11   |  123456789 |   4000   |
    | 2017-10-16   |  987654321 |   3500   |
    | 2017-11-10   |  123456789 |   3000   |
    | 2017-11-15   |  987654321 |   2500   |
    +--------------+------------+----------+

帐户

    +--------------+-------------+---------------+
    | account_no   | accountname |  loan_amount  |
    +--------------+-------------+---------------+
    |  123456789   |     John    |   15000       |
    |  987654321   |     Jane    |   20000       |
    +--------------+-------------+---------------+

从这些表中,我应该能够显示以下数据:

客户分类帐

    +--------------+------------+----------+----------------------+
    | payment_date | account_no |  amount  | outstanding_balance  |
    +--------------+------------+----------+----------------------+
    | 2017-08-10   |  123456789 |   5000   |        10000         |
    | 2017-10-11   |  123456789 |   4000   |         6000         |
    | 2017-11-10   |  123456789 |   3000   |         3000         |
    | 2017-08-15   |  987654321 |   3000   |        17000         |
    | 2017-09-15   |  987654321 |   3000   |        14000         |
    | 2017-10-16   |  987654321 |   3500   |        11500         |
    | 2017-11-15   |  987654321 |   2500   |         9000         |
    +--------------+------------+----------+----------------------+

2 个答案:

答案 0 :(得分:1)

通过使用BETWEEN UNBOUNDED PRECEDING和CURRENT行之间的行,我们可以得到结果

SELECT     p.payment_date , 
           a.account_no , 
           p.amount , 
           outstanding_balance=a.loan_amount-sum( p.amount)OVER( 
                                                PARTITION BY a.account_no ORDER BY a.account_no rows BETWEEN UNBOUNDED PRECEDING AND CURRENT row)
FROM       @payment p 
INNER JOIN @account a 
ON         p.account_no=a.account_no

结果

payment_date    account_no  amount  outstanding_balance
--------------------------------------------------------
2017-08-10      123456789   5000    10000
2017-10-11      123456789   4000    6000
2017-11-10      123456789   3000    3000
2017-11-15      987654321   2500    17500
2017-10-16      987654321   3500    14000
2017-08-15      987654321   3000    11000
2017-09-15      987654321   3000    8000

答案 1 :(得分:0)

如果是2012+,您可以使用窗口函数 sum()而非与简单连接一起使用。

示例

Select P.*
      ,outstanding = A.loan_amount - sum(P.amount) over (Partition By P.account_no Order By P.payment_date)
 From  Payment P
 Join  Account A on A.account_no=P.account_no

<强>返回

enter image description here