2

I am trying to use the QGIS Field Calculator to calculate the sum of a specific attribute ('demo_field') for features in a layer to the sum of the same attribute for features that share the same y-coordinate. However, I am encountering an issue with the following expression:

aggregate(layer:= 'layer_name', aggregate:='sum', expression:='demo_field', filter:= y(@geometry)=y(geometry(@parent)))

The error message is "Eval Error: Could not calculate aggregate for: 'demo_Field' (Cannot calculate sum on string values)."

How can I correctly calculate the sum of the attribute for each feature based on the y-coordinate?

Also, what if I dont want to give the 'layer_name' but want the current layer to be used without specifying the 'layer_name'? The reason for this is I also want to use this expression in graphical modeler.

3
  • Column data type was the first thing I checked after I received that error. I just figured out that if the column name is written without inverted comma, this works.
    – unknown123
    Dec 5, 2023 at 21:31
  • 1
    Indeed! Single quotes ' are used for textstrings. Fieldnames are used with double quotes " or without any quotes at all.
    – Babel
    Dec 5, 2023 at 21:34
  • 1
    Oops, Thank you. This is new for me as I am still learning to use expression. Thanks. :)
    – unknown123
    Dec 5, 2023 at 21:35

1 Answer 1

3

The column name should not be in inverted comma. The correct solution would be:

aggregate(
    layer:= @layer, 
    aggregate:='sum',
    expression:= demo_field,
    filter:= y(@geometry)=y(geometry(@parent))
)

This worked for me here. Also, it will be necessary to check the data type of column. If it is in string, its better to convert using to_real() or to_int().

Your Answer

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

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