rewriting COUNT DISTINCT in FOREACH as separate GROUP counts.