where conditions for associated fields and aggregate functions in select queries