I'm not sure I understand your problem... Would you mind show your code please ?
By the way, this might not be the right way to do such a sort for a fetch. You should take a look in extended attribute filters. Indeed, with them you can add new columns to the SQL statement produced by the fetch and then use them in sort_by ;).