select floor(min_angular_distance) as angular_distance_bin,
proper_motion_propagation, count(*) as n from (
select dr2_source_id, min(angular_distance) as min_angular_distance
from edr3.dr2_neighbourhood as xm
join gaiadr2.gaia_source as gaia2
on xm.dr2_source_id = gaia2.source_id
where random_index < 10000000
group by dr2_source_id
) as subquery
join edr3.dr2_neighbourhood as xm
on subquery.dr2_source_id = xm.dr2_source_id
and subquery.min_angular_distance = xm.angular_distance
group by proper_motion_propagation, angular_distance_bin
order by proper_motion_propagation, angular_distance_bin