fix regression: include rating if it is used for sorting
fix sorting according to rating

Use the same complicate SQL query for sorting as for filtering.
Move it to a constant definition.