This is kinda gnarly but I thought it was a good compromise between writing the full `GROUP BY` sql query and doing all the sorting in ruby land. Thoughts?