group/count results in SQL instead of in code. Fixes #10