A Subreport (a report within a report) is an important
feature of report generating tool. In some situations you might need more than
one query to retrieve data from database, and then you can use the subreport
feature of iReport. A report can contain more than one subreport. Each report,
including a parent report and a child report, has its own SQL query to retrieve
data from database.
Suppose you want to display the sales order details of each
salesman. For that, first you have to create the parent report that displays
all the salesmen. Now create the subreport that displays the order details of
each salesman. To create subreport select “Edit-> Insert Element ->
subreport” or click the “subreport” icons. It will open the following dialog.
Figure 1
Click the next button and write the query in the “SQL query”
text box.
Figure 2
Now click the next button. Select the required fields to
display in your subreport.
Figure 3
Continue the subreport generating process by clicking the next
button. It will open the following dialog, having different layouts to display the
subreport. Choose a suitable template from the above dialog for your report and
click the next button.
Figure 4
In the following “Subreport expression” dialog, if you
choose the first option then you have to specify the path of your subreport’s
jasper file in the “SUBREPORT_DIR” parameter.
Figure 5
Now click the finish button to get a subreport table that
displays your subreport.
Create a parameter (for example: salesmanId) in the subreport.
Now open the properties by right clicking on the subreport icons. Click the
subreport(Other) tab as shown in the following dialog.
Figure 6
To add a parameter click the Add button and fill up the
parameter name and default value expression field in the “Add/modify parameter”
dialog as shown in the following dialog.
Figure 7
Now change the subreport query to display the order details
of each salesman by passing their “salesId” as a parameter to the subreport.
The following query is used for this.
Listing 1
Select * from order_details where salesId = $P{salesmanId}
When it is run it generates a report like this:
Figure 8