Using sql, replacing a nested query with an outer join and use of python string formating

These changes appear to meet the speed requirements for this issue (e.g., study 438)