optimizing group assignation queries