complex query compiles

Need to validate logic
move single query into func
complex query, corrected some logic