Analysing point attributes within polygons

You can use Python script. Copy the script to QGIS Python Editor, change the layer names.

This script finds points in polygon, creates a set containing (district, streetname) pairs from these points and checks length of the set. If not 1, it selects that polygon. Because, in this case, at least one streetname or district is different than others.
If all pairs are the same, then length of the set will be 1.

I recommend you first to create spatial index using “Vector general > Create spatial index” tool for both point and polygon layers.

from qgis.PyQt.QtWidgets import qApp 

point_layer = QgsProject.instance().mapLayersByName("AdresSectieNN")[0]
polygon_layer = QgsProject.instance().mapLayersByName("PCPlus")[0]

qgis.utils.iface.messageBar().clearWidgets()
messageBar = qgis.utils.iface.messageBar()
progress = QProgressBar()
progress.setMaximum(polygon_layer.featureCount()) 
messageBar.pushWidget(progress)

for i, pol in enumerate(polygon_layer.getFeatures()):
    # create a set
    x = {(p["Sectie"], p["straatnaam"]) for p in point_layer.getFeatures()
                if p.geometry().within(pol.geometry())}    
    # if set (x) has 1 element, it means all points have the same district name and street name
    if len(x) != 1:
        polygon_layer.select(pol.id())

    # set current progress
    progress.setValue(i+1)
    qApp.processEvents()

iface.mapCanvas().refresh()    

enter image description here

You can use a virtual layer to create a summary table.

Go to the menu Layer > Add Layer > Add/Edit Virtual Layer... and enter the following query. Replace the layer name for yours

SELECT poly.id, pt.district, pt.streetname, count(*)
FROM my_polygon_layer poly
    JOIN my_point_layer pt ON st_intersects(poly.geometry, pt.geometry)
GROUP BY poly.id, pt.district, pt.streetname

If you only want to identify polygons having several districts/points, you can refine the query:

SELECT id, count(*) as cnt_diff
FROM (
    SELECT poly.id, pt.district, pt.streetname, count(*) as cnt_same
    FROM my_polygon_layer poly
        JOIN my_point_layer pt ON st_intersects(poly.geometry, pt.geometry)
    GROUP BY poly.id, pt.district, pt.streetname
)
GROUP BY id
HAVING COUNT(*) > 1

Leave a Comment