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?

2 Answers 2


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.


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"
  • So how could I aggregate with such a filter? For example obtaining the sum of all field 1 filtered for each value of field 2, like we can do with a sumif in excel, such as for example sumif(A$2:A$40,A2,B$2:B$40) that would be dragged down from line 2 to line 40.
    – Victor
    Sep 17, 2016 at 13:40
  • 2
    If I get it well, you can achieve it using sum("Field1","Field2"). This calls the function sum for Field1 grouped by Field2 values. Note that in the original question, you were using aggregate, which is intended to get values from other layers, whereas sum(), count(), and the like, operate on the same layer. Sep 20, 2016 at 15:43
  • Indeed, it does work. I had no inkling the sum function had group and filter components. Thanks!
    – Victor
    Sep 20, 2016 at 17:00

Replacing $currentfeature with @parent will produce the output you likely are looking for. So your aggregate command will become: aggregate( 'Layer', 'sum', "Field1" , "Field2" = attribute( @parent, 'Field2')), which allows you still aggregate based on another layer, but also filter based on the current layer you are accessing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.