Problem source: http://community.jaspersoft.com/questions/851148/loop-jasper .
The calculation of loan payments according to loan amount will involve loop operation and inter-row operation. It is difficult to write code for it using stored procedure or Scriptlets. Yet with the help of esProc, the Jasper calculation will become easier. Here is an example.
Database table loan contains loan data including loan amount, terms by the month and yearly interest rate. You need to create a Jasper grouped report in which, under each sum of loan amount, payment details per term such as payment, interest rate, principal and principal balance are listed. Below is a selection from the loan table:
The following esProc code is used for preparing the data:
|
A |
1 |
=myDB1.query(“select * from loan”) |
2 |
=A1.derive(Rate/100/12:mRate,LoanAmt*mRate*power((1+mRate),Term)/(power((1+mRate),Term)-1):mPayment) |
3 |
=A2.((t=LoanAmt,Term.new(A2.LoanID:LoanID, A2.LoanAmt:LoanAmt, A2.mPayment:payment, A2.Term:Term, A2.Rate:Rate, t*A2.mRate:interest, payment-interest:principal, t=t-principal:principlebalance))) |
4 |
=A3.conj() |
5 |
result A4 |
A1: Execute SQL to retrieve records from loan.
A2: Add two computed columns – mRate (monthly rate) and mPayment (monthly payment) to A1. Below is the result:
A3: Calculate payment details for each term based on loan information. Loop function A2.() calculates A2’s members sequentially, uses “()” to perform computation step by step(steps are separated by commas), and returns the computed result of the expression in the last step. new function is used to create a two-dimensional table. A3’s result is cascade data, as shown below:
A4: Combine the cascade data to create a two-dimensional table containing payment details for each term of every loan amount.
A5: Return A4’s result to the report. A reporting tool will identify esProc with JDBC interface as a normal database.
Then create a simple grouped table with Jasper in the following template:
Below is a preview of the finished report:
A report calls an esProc script in the same way as it calls the stored procedure. Save the above script as loan.dfx. You can invoke it with call loan() and input parameters into it from Jasper’s SQL designer.