I have a polygon with vector point civic addresses inside it. Each civic address has a different number residence. I want to sum the total number of residence inside that polygon and it populate a field in the polygon. It is easy to do it manually but I need it to auto-update if another civic address is added or the number of residence changes. I'm new to QGIS and tried an expression but it didn't seem like I was able to reference the field of another point. How would I go about doing this?
It can be done in Field Calculator with function
aggregate(). In point layer create new field with field calculator expression like this:
aggregate( layer:= 'points_layer_name', aggregate:='sum', expression:=residence_number_field_name, filter:=intersects($geometry, geometry(@parent)) )
layer is polygon layer name written like string,
aggreagate is aggregate function,
expression is field from values will be taken and
filter is filtering features based on expression (in this case interesects layer geometry with geometry of parent layer).
For more info check Aggregates QGIS documentation.
You can use virtual fields for automatic updates, but keep in mind that these fields are stored in project, not in your data. If you export the layer virtual field is exported also, but ase normal field.
You can also set the expression as Default value in Attributes Form settings in Layer Properties (Attribute form setting documentation). But in this case it will update only new or edited polygon features (not when you add or edit points). Values have to be updated manually in attribute table rewriting field itselves with
"residence_number_field_name" = "residence_number_field_name".
I also posted a similar answer for the opposite case (points taking polygons attribute values) How to refer to another layer in the field calculator?
For an auto-updating field, use the Field Calculator to create a Virtual Field.
Install the RefFunctions plugin to gain access to a variety of functions that are much easier to use than the built-in
For example, use this function in the Field Calculator to count the number of points in each polygon:
Use this expression to add up all the field values of points in each polygon:
intersecting_geom_sum( 'pointlayer', 'fieldname')
Note: Substitute the name of your point layer in the expression where it says 'pointlayer'. Substitute the field name where it says 'fieldname'.
If you want to use the built-in functions, you can indeed use the
aggregate() function as Oto Kaleb suggests. However, I think you want to calculate a
count rather than a
aggregate( 'pointlayer', 'count','',intersects( $geometry, geometry(@parent) ))
As before, substitute the actual name of your point layer where my expression says 'pointlayer'.
Note that it's not necessary to include the terms like "aggregate:=", "expression:=" etc. Those terms are included in the examples to make them easier to follow, but the function works exactly the same without them.