rewrite for-loop into single SQL