2016-12-02 298 views
1

我試圖計算表中某些數據的加權平均成熟度。SQL Server 2012:加權平均計算

SaleEventID LID(PK) CurrentUPB   Interest Rate RemainingMonths 
1   1   $100,000.00   6.100%   11.00 
1   2   $67,000.00   6.200%   360.00 
1   3   $1,400,000.00  6.300%   240.00 
1   4   $500,000.00   7.000%   100.00 
2   5   $1,400,000.00  7.100%   240.00 
2   6   $500,000.00   7.000%   100.00 

所以我試圖完成的公式是(WAM):
1)乘CurrentUPB *爲LID RemainingMonths = 1
2)做到這一點對每個匹配行WHERE SaleEventID = 1
3)SUM上述計算= $411,220,000.00 = A
4)SUM所有CurrentUPB WHERE SaleEventID = 1,這等於$2,067,000.00 = B
5)然後除以A/B = $198.95這是我的WAM

我需要考慮的是,在我的表,我將有很多貸款和每個不會被歸於同一個SaleEventID值(是不是主鍵)

我的查詢到目前爲止:

SELECT l.*, A/B FROM AS WAM 
FROM (SELECT LSX_DC_Loans l 
     (SELECT CurrentUPB * RemainingMonths FROM l WHERE LID = 1 
     ) AS A 
     (SELECT SUM (CurrentUPB) CurrentUPB FROM LSX_DC_Loans 
     WHERE SaleEventID = 1 
     ) AS B 
FROM l 
) l 

我很難找出如何做步驟2 & 4.任何幫助,例子高度讚賞。

+0

什麼是洛納? – DVT

+0

剛剛更新了錯過輸入網格中的信息的問題。 – UserSN

+0

$ 411,220,000/$ 3,967,000 = $ 103.6602健康198.95從何而來? – xQbert

回答

4

要計算WAM和WAIR是非常簡單的。想想SUMPRODUCT()在Excel

Declare @YourTable table (SaleEventID int,LID int,CurrentUPB money,[Interest Rate] money,RemainingMonths money) 
Insert Into @YourTable values 
(1,1,100000.00,6.100, 11.00), 
(1,2,67000.00,6.200, 360.00), 
(1,3,1400000.00,6.300, 240.00), 
(1,4,500000.00,7.000, 100.00), 
(2,5,1400000.00,7.100, 240.00), 
(2,6,500000.00,7.000,100.00) 


Select SaleEventID 
     ,UPB = sum(CurrentUPB) 
     ,WAM = sum(CurrentUPB*RemainingMonths)/sum(CurrentUPB) 
     ,WAIR = sum(CurrentUPB*[Interest Rate])/sum(CurrentUPB) 
From @YourTable 
Where SaleEventID = @Event 
Group By SaleEventID 

返回

SaleEventID UPB   WAM   WAIR 
1   2067000.00 198.9453 6.4564 
2   1900000.00 203.1578 7.0736 
+0

哇。你是專業人士。 – DVT

+0

太棒了!謝謝John – UserSN

+0

@DVT Nope。剛剛在銀行業度過了幾十年:) –

0

如果我正確理解你的問題,這裏就是答案

SELECT 
    l.* 
    , l1.A/l2.B AS WAM 
FROM 
    LXC_DC_Loans l 
    CROSS APPLY (SELECT SUM(CurrentUPB * RemainingMonths) AS A FROM LSX_DC_Loans WHERE SaleEventID=l.SaleEventID) l1 
    CROSS APPLY (SELECT SUM(CurrentUPB) AS B A FROM LSX_DC_Loans WHERE SaleEventID=l.SaleEventID) l2