简体   繁体   中英

Selecting first unique email address in SQL

I have a list of UserIds (which is a uniqueidentifier), Names, email addresses and relationships.

Something like

SELECT UserId, Name, Email, Relationship FROM Users

Sample data would look like:

F87B7702-F0EE-11D3-B288-0000B4A488D3  Peter peter@peter.com Member
ZZZZZZZZ-F0EE-11D3-B288-0000B4A488D2  Joan  peter@peter.com Principal
AAAAAAAA-F0EE-11D3-EEEE-0000B4A488D3  Bob   bob@bob.com     Principal

Relationship can be either be 'Principal' or 'Member', but a principal user can also be a member.

An email address isn't specific to a user (often a member user will have the same email address as a principal user).

I need to ensure that I only select 1 user per email address so that the same person won't be emailed twice. If there are 2 emails for the same user I need to select the principal record.

What's the easiest way to do this, bearing in mind that you can't do a max on a uniqueidentifier field? For the sample data I gave above I would need to return only the second and third record.

I was leaning towards ordering by Relationship, doing a group by and then max but I don't think that's possible.

Output required is UserId, Name, Email.

The ORDER BY in ROW_NUMBER() will allow you to choose how to prioritise your emails. Such as how to deal with an email with no Principle but multiple Members (maybe add , Name ASC so the member with the first alphabetically ordered name gets chosen?)

SELECT
  *
FROM
(
  SELECT
    *,
    ROW_NUMBER() OVER (PARTITION BY email ORDER BY Relationship DESC) AS sequence_id
  FROM
    yourTable
)
  AS sequenced_table
WHERE
  sequence_id = 1

I didn't quite understood you, but if you want to get email only once, preffering the principle user this code will do:

select UserId, Name, Email, Relationship
from Table
where Relationship='Principle' or ( Relationship='Member' and Email not in
(
select Email
from Table
where Relationship='Principle'
)
)

This will give you the second and third lines. If there are more conditions- expand your example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM