How can I use WHERE clause to filter in the OVER clause?
i.e. from the following data
LoanID | Principal | Tenor | AmortizingPrincipal ---------------------------------------- 1 20000 1 5000 1 20000 2 5000 1 20000 3 5000 1 20000 4 5000 I need a fourth virtual column with the Balance Principal in each Tenor like the following:
LoanID | Principal | Tenor | AmortizingPrincipal | BalancePrinicpal ----------------------------------------------------------- 1 20000 1 5000 20000 1 20000 2 5000 15000 1 20000 3 5000 10000 1 20000 4 5000 5000 Something like this:
SELECT BalancePrincipal = Principal - SUM(AmortizingPrincipal) OVER(PARTITION BY LoanID WHERE Tenor < this row's tenor) UPDATE:
The following query gives me the desired result:
SELECT L1.* ,BalancePrincipal = AL1.Principal - ISNULL(Cumulative.AmortizingSum,0) FROM Loan L1 CROSS APPLY ( SELECT AmortizingSum = SUM(AmortizingPrincipal) FROM Loan L2 WHERE L1.LoanID = L2.LoanID AND L1.Tenor > L2.Tenor ) Cumulative
Can it be bettered?