rewrite for-loop into single SQL
Merge pull request #1 from immon/master

rewrite for-loop into single SQL