rewrite for-loop into single SQL

Optimize for-loop into single SQL as you described at your job posting.