You can do the following:
You have run the "Join Attributes by nearest" on layer 1 & layer2 features. Maximum nearest neighbors: 8, in my cases I added a max distance as well.
This is where you get a new layer nnjoin
which attribute table has layer1 feature ids
, layer2 feature ids
, n
and distance
, ...

What you can do to turn this in a layer with one entry for each layer1
feature, and 8 columns with the layer2
nearest feature "id"
s, is to use some SQL in a Virtual layer through Layer > Add Layer > Add/Edit Virtual Layer
.
Add a virtual layer
with the following query:
select nnj.geometry, nnj.osm_id,
max(nnj.osm_id2_1) as osm_id2_1, max(nnj.osm_id2_2) as osm_id2_2,
max(nnj.osm_id2_3) as osm_id2_3, max(nnj.osm_id2_4) as osm_id2_4,
max(nnj.osm_id2_5) as osm_id2_5, max(nnj.osm_id2_6) as osm_id2_6,
max(nnj.osm_id2_7) as osm_id2_7, max(nnj.osm_id2_8) as osm_id2_8
from (select geometry,osm_id,
case when n = 1 then osm_id2 end as osm_id2_1,
case when n = 2 then osm_id2 end as osm_id2_2,
case when n = 3 then osm_id2 end as osm_id2_3,
case when n = 4 then osm_id2 end as osm_id2_4,
case when n = 5 then osm_id2 end as osm_id2_5,
case when n = 6 then osm_id2 end as osm_id2_6,
case when n = 7 then osm_id2 end as osm_id2_7,
case when n = 8 then osm_id2 end as osm_id2_8
from nnjoin) as nnj
group by nnj.osm_id
Which provides you with the following layer and attribute table:
