select round(angular_distance) as mas, count(*) as n
from edr3.dr2_neighbourhood as xm
join gaiadr2.gaia_source as gaia2
on xm.dr2_source_id = gaia2.source_id
where dr2_source_id = dr3_source_id
and gaia2.random_index < 10000000
group by mas
order by mas
select mas, count(*) as n
from (
select dr2_source_id, min(round(angular_distance)) as mas
from edr3.dr2_neighbourhood as xm
left outer join edr3.gaia_source as gaia3
on gaia3.source_id = xm.dr2_source_id
join gaiadr2.gaia_source as gaia2
on xm.dr2_source_id = gaia2.source_id
where gaia3.source_id is null
and gaia2.random_index < 10000000
group by dr2_source_id
) as subquery
group by mas
order by mas
select round(angular_distance) as mas, count(*) as n
from edr3.dr2_neighbourhood as xm
left outer join edr3.gaia_source as gaia3
on gaia3.source_id = xm.dr2_source_id
join gaiadr2.gaia_source as gaia2
on xm.dr2_source_id = gaia2.source_id
where gaia3.source_id is null
and gaia2.random_index < 10000000
group by mas
order by mas