Skip to content
Advertisement

Returning multiple columns from a table with no duplicates of one of the columns

I have a SQL Server table containing columns id and email (amongst others). The id column contains distinct values, the email column may contain duplicates. I can retrieve all the distinct email values quite easily, however, what I actually need is a list of id values that have distinct email values. For example

id    email
1     fred@bloggs.com
2     joe@bloggs.com
3     fred@bloggs.com

I am looking for returned id values of 1 and 2 (or 2 and 3 – it doesn’t matter which of the id values is picked when there is a duplicate email).

For further background information, the table contains a list of members. When sending messages to members, the message interface needs the member id. However, I don’t want to send duplicate messages to any email address, and when there are members with the same email address it doesn’t matter which member is sent the message.

Advertisement

Answer

Just use aggregation:

select min(id) as id, email
from t
group by email;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement