Split up sort SQL to ensure the query is valid

This should fix the broken search and sort functionality on Siftr.

The query can end up having `JOIN`, `WHERE`, and `GROUP`/`ORDER`, and they need to come in that order. A few of the existing search fragments needed to be split up in order to ensure that happens.