计算来自唯一电子邮件的域数

时间:2017-10-23 09:07:40

标签: mysql sql

我有一个包含电子邮件的表格,我想知道我有多少个独特的域名。相同的电子邮件数量。

email                    suscriber_id
----------------------------------------------
pepe@yahoo.es            1
pepe@yahoo.es            1
jaime@yahoo.es           2
jese@gmail.com           3
pepe@yahoo.es            1

如果我尝试此查询:

SELECT substring(email,LOCATE('@',email),LENGTH (email)) as domain, count(substring(email,LOCATE('@',email),LENGTH (email))) as counter from tracks group by domain";

domain                  counter
----------------------------------------------
yahoo.es                4
gmail.com               1

但我想要这个结果:

domain                  counter
----------------------------------------------
yahoo.es                2
gmail.com               1

1 个答案:

答案 0 :(得分:2)

您正在寻找COUNT DISTINCT。您可以使用SUBSTRING_INDEX轻松访问这两个子字符串:

select 
  substring_index(email, '@', -1) as domain,
  count(distinct substring_index(email, '@', 1)) as counter 
from tracks 
group by substring_index(email, '@', -1);

您可能会发现这更具可读性:

select domain, count(distinct account) as counter
from
(
  select 
    substring_index(email, '@', -1) as domain,
    substring_index(email, '@',  1) as account
  from tracks 
) emails
group by domain;