SQL选择与多个字段不同,只返回一行

时间:2012-07-03 09:22:39

标签: sql-server unique distinct-values

我在SQL Server中有一个包含以下列的表:

MEMBERID, MEMBEREMAIL, FATHEREMAIL, MOTHEREMAIL, MEMBERNAME

MEMBERID是PK。这三个电子邮件列不是唯一的,因此相同的电子邮件可能会在同一行和多行中多次出现。

我正在尝试提取一个唯一的电子邮件列表,每封电子邮件也会获得memberidmembername(与哪条记录无关。)

例如,如果我有三行:

1   x@x.com   y@y.com   y@y.com   Mark
2   z@z.com   y@y.com   x@x.com   John
3   x@x.com   y@y.com   z@z.com   Susan

我希望收到三封电子邮件(x@x.com, y@y.com, z@z.com),并为每一封电子邮件显示MEMBERID。它不是MEMBERID(例如x@X.com我不在乎我是否得到值1和Mark或2和John或3和Susan,只要x@x.com只出现{{1}}一次在结果中。

如果我在尝试返回电子邮件和memberid以及成员名时使用DISTINCT,我当然会获得所有行。

2 个答案:

答案 0 :(得分:3)

您可以使用子查询来规范化所有电子邮件。然后,您可以使用row_number按电子邮件过滤掉一个memberid, membername

select  *
from    (
        select  row_number() over (partition by email order by memberid) as rn
        ,       *
        from    (
                select  MEMBERID
                ,       MEMBERNAME
                ,       MEMBEREMAIL as email
                from    YourTable
                union all
                select  MEMBERID
                ,       MEMBERNAME
                ,       FATHEREMAIL
                from    YourTable
                union all
                select  MEMBERID
                ,       MEMBERNAME
                ,       MOTHEREMAIL
                from    YourTable
                ) as emails
        ) num_emails
where   rn = 1

您还可以使用UNPIVOT子句规范化电子邮件,如下所示:

select  *
from    (
        select  row_number() over (partition by email order by memberid) as rn
        ,       *
        from    (
                select  MEMBERID
                ,       MEMBERNAME
                ,       email
                from    YourTable
                unpivot (
                                email
                        for     emailOwner
                        in      (
                                MEMBEREMAIL,
                                FATHEREMAIL,
                                MOTHEREMAIL
                                )
                        ) as u
                ) as emails
        ) num_emails
where   rn = 1

SQL Fiddle处尝试两个版本:

答案 1 :(得分:0)

此代码将为您提供正确的不同电子邮件组: 然后你可以从查询成员中创建一个游标,然后用this concept得到每个memberid的邮件的逗号分隔列表我会创建一个输出表,如果你需要它以备将来使用它会更容易存储过程以创建自定义表

select mem.*, mails.MEMBEREMAIL
from (
    select MEMBERID,max(MEMBERNAME) as MEMBERNAME
    from table
    group by MEMBERID
)  as mem 
inner join 
(
    select distinct MEMBERID, MEMBEREMAIL
    from (
        select MEMBERID, MEMBEREMAIL
        from table
        union
        select MEMBERID, FATHEREMAIL
        from table
        union
        select MEMBERID, MOTHEREMAIL
        from table
    ) as mail
) as mails on mem.MEMBERID = mails.MEMBERID