Custom views sort handler
Use aggregate and set the option for distinct results. Aggregate is similar to GROUP BY in SQL so be careful what fields you include. If you really need to do it with custom code set a tag for your view's query in advanced settings and then use this tag to alter your query by implementing hook_query_alter or hook_query_TAG_alter in a custom module
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_query_TAG_alter/7