2

I am working in QGIS 3.24.0. I have 200 vector layers in the form of circular buffers (same size, different extent) and a single layer of points (n=1,000 or so) contained within those buffers. 2 of the buffers are shown below as an example. Each buffer has ~5 points within. I want to select a random point from within each buffer.

How do I accomplish this?

enter image description here

1
  • Dont you mean one polygon layer with 200 polygons in it?
    – Bera
    Commented Jun 16, 2022 at 17:21

1 Answer 1

2

You can achieve this using a virtual layer.

Go to the menu Layer > Add Layer > Add/Edit Virtual Layer... and enter the following query. Feel free to add/remove any field of interest from the two layers.

This query makes use of the fact that in SQLlite a group by without an aggregator (min, max etc) will return values of the "first" row. By specifying a random order in the subquery, we effectively get a random point per polygon.

You can then export the virtual layer to a shapefile or else. Note that each time you pan the map the virtual layer is recomputed and therefore a different random point will be selected.

select * 
from
(
 select a.id as poly_id, b.*
 from mypoly_layer a 
  join mypoint_layer b 
   on st_intersects(a.geometry, b.geometry)
 order by random()
 )
group by poly_id

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.