Reimplement groupby+sum without rails (direct SQL)