# Calculating field AVG from B layer 3 nearest points to each A layer point

I wonder how to calculate statistics (in my case average) of one point layer field (let say B layer) and assign them to each point of A layer. Statistics should be calculated from 3 nearest B layer points that are closest points to the point from A layer. My software is QGIS 3.4.15. For the above example:

• Let say that I want to calculate avg of 'Price' attribute that contains B layer.
• The AVG(B2.Price, B3.Price, B4.Price) should be assigned to point A1 of A layer.
• The AVG(B5.Price, B6.Price, B7.Price) should be assigned to point A2 of A layer.
• The AVG(B5.Price, B8.Price, B9.Price) should be assigned to point A3 of A layer.
• It would be great to assign also the distance to the 3rd point.

Sorry, I can not provide an answer for QGIS 3.4, but for 3.8+, in case you have a chance to update. The tool you need for this is called `join attributes by nearest`, which was introduced with 3.8. For earlier versions there is a plugin called NNJoin, but this allows only to join one nearest feature, not several.

1. I have two point layers in UTM (so join distance is in meters). A contains id's and B contains random prices.
2. Run the tool `join attributes by nearest` from processing toolbox and set it up the following: Use A as Input layer and B as Input layer 2. Set maximum nearest neighbors to 3 and run the tool.

1. Now open the output layer. It will have 3 duplicates of layer A including the attributes of the 3 nearest neighbors of B. 1. Open the field calculator and create a new float or integer field. Add the expression `mean("Price", group_by:="id")`: Of course you can use any other expression than mean(). E.g. max, min, and so on.

1. The Joined Layer will now contain your result: You can now delete the duplicates and no longer needed columns if you wish to.