SQL Server数据库表具有以下列:
[company]
:发送电子邮件的公司名称[email1]
:是主要的电子邮件收件人[email2]
:辅助电子邮件收件人(可为空)该数据库包含数百个独特的公司。
我想计算在[email1]
和[email2]
上每个[company]
总共发送了电子邮件的数量。
编辑:在下面添加了一个示例表,请注意,在一种通信中出现在[email1]
中的电子邮件ID可能在另一通信中出现在[email2]
中,反之亦然:
company email1 email2
---------------------------------------------------
company1 person1@abc.com person2@abc.com
company1 person2@abc.com person3@abc.com
company2 person1@xyz.com person2@xyz.com
company2 person1@123.com person2@123.com
所以结果应该像这样:
company numUniqueEmails
---------------------------------
company1 3
company2 4
答案 0 :(得分:0)
您可以使用此查询为每个公司计算唯一的电子邮件ID:
select company, count(*) numUniqueEmails
from (
select distinct company, email1 from tablename
union
select distinct company, email2 from tablename
) tbl
group by company
使用CTE可以达到相同的结果
with cte
as (
select distinct company, email1 from tablename
union
select distinct company, email2 from tablename
)
select company, count(*) numUniqueEmails
from cte
group by company