说我有下表,Peter和Halla,
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
我们只检索电子邮件的实例? (这意味着我们最终会有不同的电子邮件)
答案 0 :(得分:0)
试试这个
;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
答案 1 :(得分:0)
尝试类似
的内容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