A little addition to Gordon Linoff's solution: In order to not get the relations double (i.e. 1-3 and 3-1) I added the where clause:
select ab1.a as a1, ab2.a as a2, count(*)
from a_b ab1 join
a_b ab2
on ab1.b = ab2.b and ab1.a <> ab2.a
where ab1.a < ab2.a
group by ab1.a, ab2.a