Optimize builiding query

Use `reduce` with generators instead of nested for loops with extra variables and `if`s.
Merge pull request #1 from MagicSolutions/master

Optimize builiding query