【问题标题】:Retrieve an instance for an email检索电子邮件的实例
【发布时间】:2017-01-23 02:20:10
【问题描述】:

假设我有下表,彼得和哈拉,

Name    Age occupation  BillingContactEmail
-------------------------------------------
Peter   44  Salesman    a@a.com
Andy    43  Manager     a@a.com
Halla   33  Fisherman   b@b.com

如何构造一个 SQL 来返回这个数据集:

Name    Age occupation  BillingContactEmail
-------------------------------------------
Peter   44  Salesman    a@a.com
Halla   33  Fisherman   b@b.com

我们只检索电子邮件的实例? (意味着我们最终会有不同的电子邮件)

【问题讨论】:

  • 你是如何选择彼得而不是安迪的?
  • @Bohemian 随机会做

标签: sql sql-server-2016


【解决方案1】:

试试这个

;with cte (rowno, Name, Age, Occupation, BillingContactEmail)
as (
    select row_number() over (partition by BillingContactEmail order by BillingContactEmail), Name, Age, Occupation, BillingContactEmail 
    from myTable
)
select Name, Age, Occupation, BillingContactEmail from cte 
where  rowno = 1

您可能需要考虑为列编制索引以获得更好的性能。

当然,如果您想明确选择谁,您需要相应地调整order by

如果年龄/职业无关紧要,您始终可以通过电子邮件将姓名分组,如下所示:

select  stuff((select concat( ',', Name) from myTable a where a.BillingContactEmail = t.BillingContactEmail   for xml Path('')), 1, 1, '') as Name, 
        BillingContactEmail 
from myTable t
group by BillingContactEmail

输出:

Name          BillingContactEmail 
------------- --------------------
Peter,Andy    a@a.com
Halla         b@b.com

【讨论】:

    【解决方案2】:

    试试类似的东西

    Select distinct  email,
            (
               Select tb1.First_Name+ ','  AS [text()]
               From dbo.table1 tb1
               Where tb1.Email = 'a@a.com'
               For XML PATH ('')
            ) [Students]
    From dbo.table2
    WHERE Email = 'a@a.com'
    

    输出:

    Name          BillingContactEmail 
    ------------- --------------------
    Peter,Andy,    a@a.com
    

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 2010-09-22
      • 1970-01-01
      • 1970-01-01
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多