fixed sql calls by separating subqueries