2017-07-06 126 views
3

目前我正在努力解决以下问题:
我有两个表(合同&摊销)。SQL Server:计算摊销

合同:合同信息与欠款
摊销:支付&摊销金额的日期


我期望的结果是与合同和减少 奥斯坦丁量的表。

;WITH CTE AS 
(
     SELECT con.ID 
       ,con.outstanding 
       ,amo.amortization 
       ,amo.amo_date 
       ,ROW_NUMBER() OVER (PARTITION BY con.ID 
             ORDER BY amo.amo_date asc 
           ) as rn  
      FROM contract con 
    INNER JOIN amort amo 
      ON amo.contractID = con.ID 
) 
SELECT ID 
     ,outstanding 
     ,outstanding - amortization as new_outstanding 
     ,amo_date 
    FROM CTE 

目前我得到这个结果 - 这当然是错误的,因为只有一个摊销计算的new_outstanding:

ID outstanding  new_outstanding  amo_date 
1 100000   90000    01.08.2017 00:00:00 
1 100000   80000    01.09.2017 00:00:00 
1 100000   50000    01.10.2017 00:00:00 
1 100000   90000    01.11.2017 00:00:00 
1 100000   90000    01.12.2017 00:00:00 

我期望的结果将是:

ID outstanding  new_outstanding  amo_date 
1 100000   90000    01.08.2017 00:00:00 
1 100000   70000    01.09.2017 00:00:00 
1 100000   20000    01.10.2017 00:00:00 
1 100000   10000    01.11.2017 00:00:00 
1 100000   0     01.12.2017 00:00:00 

任何简单的想法,以简单的方式解决这个问题?

Rextester:http://rextester.com/SBLT77863

提前感谢!

回答

5

我想你只需要一个累计总和:

SELECT con.ID, 
     con.outstanding, 
     amo.amortization, 
     amo.amo_date, 
     (con.outstanding - 
     sum(amo.amortization) over (partition by amo.contractId 
            order by amo.amo_date) 
     ) as new_outstanding 
FROM contract con INNER JOIN 
    amort amo 
    ON amo.contractID = con.ID; 
+0

该死!那很快。这很容易。非常感谢。似乎我只是想完全错误的方向。 –