# Mean of polygons area within another polygon layer

I have the following layers :

• Sectors (polygons limited by the black lines)
• Houses (polygons in light blue)

I have created the area attribute in the Houses table. I have also created an attribute that represents the centroid of the geometry.

I would like to calculate the mean area of Houses located in each sector and add it as an attribute of the Sectors table. A house is considered "in the sector" if its centroid is in the sector (to avoid problems with houses over 2 different sectors).

I don't know how to do this "group by" operation and haven't found answers searching this stack. • Start with Intersect then try for example Group Stats etc. – BERA Apr 5 '20 at 11:29
• In DB manager you can use SQL on virtual layers. – Zoltan Apr 5 '20 at 11:54

Try this expression on your `Sectors` layer's attribute table:

``````aggregate(layer := 'Houses',
aggregate:= 'mean',
expression:= "area",
filter:= within(centroid(\$geometry), geometry(@parent)))
``````

A quick test output ("ave" field) below: You can calculate the mean area of houses using the Field Calculator to create a new field in the Sectors layer.

Use this expression

``````
(to_string(array_sum(aggregate(
layer:= 'Houses',
aggregate:='array_agg',
expression:=\$area,
filter:=contains(geometry(@parent), \$geometry)))))
/
(aggregate(
layer:='Houses',
aggregate:='count',
expression:=\$id,
filter:=intersects(geometry(@parent), (\$geometry))))
``````

The first part of the expression calculates the sum of all the Houses areas inside each sector. The second part calculates the number of Houses inside the sector. A simple division of the first number by the second will give you the request information