SQL查询:仅显示一个电子邮件地址

时间:2015-11-30 17:00:52

标签: sql-server select count

我有一个查询,我想显示的只有一个电子邮件地址。

说明

下面是三个3个不同的查询。第一个查询给出位置,第二个查询给出部门,最后一个查询是针对在特定日期之间参加事件的客户。在进行此查询后,我显示的是具有行号的电子邮件地址,并且电子邮件存在于特定部分。

with temp as  (
    Select Distinct 'A' AS Part, ID, Email Address 
    from c_detail
        where a.status = 1
        and State IN ('NY','FL','CA','IL','GA') 
        and City IN ('Albany','Long Beach','Middletown','New York','Miami','Orlando','Tempa','Jacksoneville','Los Angeles','San Diego','Chicago','Aurora','Rockford','Atlanta','Savannah','Athens')
        Union

    Select Distinct 'B' AS Part, ID, Email Address 
    from c_detail
        where a.status = 1
        AND deptno IN ('5','9','8','7')

    UNION

    Select Distinct 'C' AS Part, ID, Email Address 
    from c_detail
        where a.status = 1
        AND AttDate between 2015/01/08 and 2015/01/25


) select *, Row_number() over ( partition BY email ORDER BY email) rn from temp

输出

Part    ID          Email               rn
A       21345       jjohnson@abc.com    1
A       73245       tferna@abc.com      1
B       21356       tferna@abc.com      2
A       13343       scardon@abc.com     2
C       14564       bmethews@abc.com    3   
A       54656       pwilliams@abc.com   5
B       34156       pwilliams@abc.com   2
C       12368       pwilliams@abc.com   3
A       54631       kpearce@abc.com     2   
A       87966       mjordan@abc.com     1

现在,我想只显示一个来自各个部分的电子邮件地址。在我的输出表中有两个电子邮件地址,它们位于不同的部分(部分)。

那么,即使它存在于另一个部分,我怎么才能只显示一个电子邮件地址。

2 个答案:

答案 0 :(得分:1)

将结果查询用作另一个CTE并将代码更改为以下

select *, Row_number() over ( partition BY Part ORDER BY Part) rn from temp

之后你可以从cte WHERE rn = 1

中编写select *

答案 1 :(得分:0)

回答我的问题

`with temp as  (
    Select Distinct 'A' AS Part, ID, Email Address 
    from c_detail
        where a.status = 1
        and State IN ('NY','FL','CA','IL','GA') 
        and City IN ('Albany','Long Beach','Middletown','New York','Miami','Orlando','Tempa','Jacksoneville','Los Angeles','San Diego','Chicago','Aurora','Rockford','Atlanta','Savannah','Athens')
        Union

    Select Distinct 'B' AS Part, ID, Email Address 
    from c_detail
        where a.status = 1
        AND deptno IN ('5','9','8','7')

    UNION

    Select Distinct 'C' AS Part, ID, Email Address 
    from c_detail
        where a.status = 1
        AND AttDate between 2015/01/08 and 2015/01/25


), temp_result AS ( select *, Row_number() over ( partition BY email ORDER BY email) rn from temp)
select * from temp_result WHERE rt.rn=1`

谢谢你@AdrianChodkowski