QGIS – Inserting Labels in Layouts with Expressions

labelinglayoutsqgis

I'm using the following expression that works correctly and labels a layer of points with the count function:

case when "GRUP" = 1 then 
aggregate('points','count', "VAUEX", "VAUEX" IN ('A'))
else
null
end

The 'points' layer has two fields "GRUP" and "VAUEX". This expression filters the records from the "GRUP"='1' field and "VAUEX"='A' and counts the total.

I am trying to use this same expression in the Layout Label object with the following syntax:

[%case when "GRUP"=1 then
aggregate('points','count', "VAUEX", "VAUEX" IN ('A'))
else
null
end%]

I can't get it to work. How can I correct this expression so that it works and shows the total value?

Best Answer

The problem is that "GRUP" = 1 is meaningless to the Label object in the Layout, there is no context of the layer for which to evaluate the expression.

However, you can use a compound filter by combining your two clauses. In the aggregate function you are declaring which layer to use so the filter can evaluate successfully.

[%
  aggregate(
    'points',
    'count', 
    expression:= "VAUEX", 
    filter:= "VAUEX" in ('A') and "GRUP" = 1
  )
%]

The else null is also redundant, as this is done implicitly for features that don't match the filter.

Related Question