2017-07-06 107 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

該死!那很快。這很容易。非常感謝。似乎我只是想完全錯誤的方向。 –