Optimize builiding query

Use `reduce` with generators instead of nested for loops with extra variables and `if`s.