[GIS] Counting number of features within another feature using aggregate function in the QGIS Field calculator

aggregationfeature-countfield-calculatorpoint-in-polygonqgis

My data: 1 polygon layer + 1 point layer
My target: Calculate the number of points and the sum of a field within each polygon using the aggregate function in the QGIS field calculator.

I know I can simply use the QGIS functions "Join attributes by location (summary)" or "Count points in polygon" but I'm interested in the aggregate function in the field calculator since I donĀ“t understand exactly its meaning.

Using

aggregate('hh', 'sum', "sum_pop")

'hh' – the name of the point layer
'sum_pop' – the name of the attribute field from the hh layer (sum of the population of a point)

I get the sum of the whole field in the attribute table, so each feature has the same value.

aggregate_result_nok

How can I change the code for the aggregate function to calculate the sum of a value based on the number of points in each polygon feature and the number of features within a polygon so I get different values for each polygon?

example1

ecample2

evaluation error

Best Answer

This expression will count the number of populated places for each country:

aggregate(layer:='ne_110m_populated_places',
          aggregate:='count',
          expression:=name,
          filter:=contains(geometry(@parent), $geometry)
          )

you can use the same expression to get the sum, just change the aggregate to 'sum' and the expression to the field name to summarize.

Related Question