How to select first row from a join that returns multple rows on the primary key
SELECT
A.PersonName, A.Email
FROM
(
Select Person.PersonName, Email.Email
,ROW_NUMBER() OVER(PARTITION BY Person.ID ORDER BY Email.Email) AS RN
From person
left join Email on Person.ID=Email.PersonId
) A
WHERE A.RN = 1
I would use an outer apply for this, I find it more readable.
Select Person.PersonName, coalesce(Email.Email,'No email found.') as Email
From person
outer apply (
select top(1) Email.Email
from Email
where Person.ID=Email.PersonId
order by <whatever suits you>
) as Email;
As it does not matter which email shows up. I think that the following one is very direct.
Select Person.PersonName, MIN(Email.Email)
From person
left join email
on Person.ID=Email.PersonId
group by Person.Id, Person.PersonName