Modify ancestry order scopes to work with SELECT DISTINCT

Move case statement into part of the select. Fixes #128