Fancy SQL to handle contest problem ranking