[GIS] Aggregating with attribute($currentfeature) filter in QGIS

aggregateexpressionfilterqgis

Why doesn't the filter work (4th variable passed into the aggregate function) when I try to use in the field calculator an expression of this type:

aggregate('Layer', 'sum', "Field1" ,  "Field2" = attribute($currentfeature, 'Field2'))

It returns the total sum of "Field1" rather than applying the filter.
In the aggregate function, such a filter seems to be always true, while by itself, it works.

Is it not possible to use feature-based expressions with the aggregate function, or can it work if I modify the expression?

Best Answer

It turns out that the filter you are passing to the aggregate function always returns True for any feature.

"Field2"  = attribute( $currentfeature, 'Field2')

In other words, what you have at the left hand side of the condition is the same as you have on the right hand side.

Why?

Because "Field2" gets the value of field Field2 for the current feature, and that's exactly what the attribute function will do, because you're asking for the value of the field called 'Field2' (second parameter) for the current feature (first parameter: $currentfeature).

Keep in mind that the filter expression can only access fields and values from the referenced layer ('Layer' in your example) and not from the layer you're going to store results into.

So, you need to pass a filter that not always evaluates to True, or it will not make sense to pass it at all.

Example of valid filters (it would depend on your field values, of course):

"Field2" = 185
"Field2" = 'abc'
"Field2" = attribute( $currentfeature, 'Field3' )
"Field2" = "Field3"
Related Question