QGIS Label Error – Fixing Label in QGIS Layout Returns Zero but Preview Displays Correct Value

dynamic-textfields-attributeslabelingprint-composerqgis

I am new to QGIS layout. I would like to display a label showing the proportion of table values meeting set criteria. Please see below:

round((count(score,score<=3)/count(score))*100,2)||'%'

In the above, score is a field in an attribute table. The above expression generates the correct value in the preview, but shows 0% in the text box on the print layout map.

How do I display the preview text on the print map, and why is the above expression unusable?

Best Answer

Functions with layer defined by context

The function count is an aggregate function that should be used when the layer could be defined by the context where the expression is evaluated (if you use this formula in a labelling rule the layer will be defined).

As you are evaluating this expression in a text box within a layout, there is no layer defined by context. You have to use aggregate function to get the count of feature from a specific layer.

A solution (based on my understanding)

Your expression is round((count(score,score<=3)/count(score))*100,2)||'%'

Based on my understanding, you try to calculate the share in percent of features that have a score attribute lower than 3.

Note : As you have not specified filters, all the features will be used for this calculation (even the one outside the layout map).

Your formula should look like this :

round((
  aggregate ('your_layername_here','count', "score", "score"<=3)
  / aggregate ('your_layername_here','count', "score")
)*100,2)||'%'
Related Question