sql >> Base de Datos >  >> RDS >> Sqlserver

SQL Server 2012:Cálculo del promedio ponderado

Calcular WAM y WAIR es bastante simple. Piense sumproduct() en 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

Devoluciones

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