QGIS Field Calculator – Aggregating and Calculating Ratios Based on Y-Coordinate

aggregationattribute-tablefield-calculatorqgisspatial-query

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.

Best Answer

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().