This code here really looks like you are imitating an inner join. You throw out cases where either side has no input. You manually build the cross produce within a group. This is exactly what the join would do for you.

Why not use a join directly?