Another blast from the past - fix distinct/order behavior borked by d59eba65f

While the SQL we test for is valid syntax - the result it produces makes
zero sense for these resultset arguments. Reshuffle the distinct construction
and reuse the codepah for order_by rewrites.

This is a heavy change, but it is *extremely unlikely* anyone was relying on
the previous behavior - any aggregate value would have been wrong...