Grouping and null values in Jasper reports

Nulls are not created equal – except in Jasper. In somes cases you want to do grouping on the report based on some field that might also contain null values. Jasper treats these null values as equal, meaning that they go to the same group. This means you only get one group header and one group footer for all those rows with “null” group expression.

Luckily there is an easy workaround for this. You need to supply a group expression that gives unique (inside the group) values if the main group by field equals to null.

Here is a simple example:

($F{parent_id} != null ? $F{parent_id}.toString() : "_" + $V{myGroup_COUNT}.toString())

This reads: If parent_id is not null, use the parent_id as the group expression. Otherwise concatenate underscore (“_”) to the myGroup_COUNT variable and use that.

The myGroup_count variable is created automatically when you create a group and it counts the rows inside the group. The underscore is concatenated to value just to make sure we don’t get conflicts with real parent_id.