[英]Selecting first unique email address in SQL
I have a list of UserIds (which is a uniqueidentifier), Names, email addresses and relationships.我有一个 UserIds 列表(这是一个唯一标识符)、名称、email 地址和关系。
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.关系可以是“Principal”或“Member”,但主要用户也可以是成员。
An email address isn't specific to a user (often a member user will have the same email address as a principal user). email 地址并非特定于用户(通常成员用户将具有与主要用户相同的 email 地址)。
I need to ensure that I only select 1 user per email address so that the same person won't be emailed twice.我需要确保每个 email 地址只有 select 1 个用户,这样同一个人就不会收到两次电子邮件。 If there are 2 emails for the same user I need to select the principal record.
如果同一用户有 2 封电子邮件,我需要 select 主体记录。
What's the easiest way to do this, bearing in mind that you can't do a max on a uniqueidentifier field?记住你不能在 uniqueidentifier 字段上做最大值,最简单的方法是什么? 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. Output 需要是用户 ID、名称、Email。
The ORDER BY
in ROW_NUMBER() will allow you to choose how to prioritise your emails. ROW_NUMBER() 中的
ORDER BY
将允许您选择如何优先处理您的电子邮件。 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?)例如如何处理没有原则但有多个成员的 email (可能添加
, Name ASC
以便选择第一个按字母顺序排列的成员?)
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:我不太了解您,但是如果您只想获得一次 email,请向主要用户提供此代码:
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.
如果有更多条件 - 扩展您的示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.