I have a sql server table as follows
- EmailId
- PersonId
- IsPreferred
A specific PersonId can have more than 1 email, in which case one of the email addresses MIGHT be preferred. How can I select one email for each PersonId ensuring that if there is a preferred email that is the one selected. If there is no preferred email for a PersonId any email can be selected.
Select with “ORDER BY ISPREFERRED DESC”, then take the first result row.
Generally, in case ordering is not convenient this way, you may use a UNION of subqueries, with an additional “constant” value column “1”, “2” .. in each part of the UNION, then sort (descending, so highest value comes first) on that column. Again, take the first one.