replace distinct by more effective subquery