Selecting point with maximum value for each polygon

The user of a SQL query is appropriate for your problem.

I created 2 tables: one with 2 polygons and another with 5 points.

enter image description here

Then I go to the database manager > Virtual layers > and open a SQL query window

I execute the following request :

--First part : For each polygon, the prices of all the points that are contained.
-- An identifier (fid) is generated for each polygon in descending order of price.

WITH all_price AS
 (SELECT row_number() over(partition by poly.id_poly  ORDER BY point.price DESC) as fid, 
 poly.id_poly, point.id, point.price
 FROM poly, point
 WHERE St_contains(poly.geometry,point.geometry)
 ORDER BY poly.id_poly, point.price)

 --When fid is equal to 1, it means that it is the highest price.
 SELECT all_price.id_poly, all_price.id, all_price.price
 FROM all_price 
 WHERE fid = 1

Result of the temporary table all_price on the left and the final result on the right. If you don't understand the request, I can give you more explanations.

enter image description here


dpr = layer_polygon.dataProvider()
max_value_index = layer_polygon.fields().indexFromName('max_value')

for pol in layer_polygon.getFeatures():
    g = pol.geometry()
    req = QgsFeatureRequest(g.boundingBox()) # for performance
    prices = [p["price"] for p in layer_point.getFeatures(req) if g.contains(p.geometry())]
    dpr.changeAttributeValues({pol.id(): {max_value_index: max(prices)}})

enter image description here

Tags:

Pyqgis

Qgis 2