1

我正在尝试确定每个域、雅虎、谷歌、美国在线的订阅者数量......

这是我想出的,但它并没有像我想象的那样分组

select SUBSTRING(EmailAddress, PATINDEX('%@%', EmailAddress) +1, LEN(EmailAddress) -PATINDEX('%@%', EmailAddress)) As [Domain], COUNT(SUBSTRING(EmailAddress, PATINDEX('%@%', EmailAddress) +1, LEN(EmailAddress) - PATINDEX('%@%', EmailAddress))) As [Count]
from Subscribers
GROUP BY EmailAddress

结果看起来像这样

yahoo.com   1
gmail.com   1
yahoo.com   1

我想要更多这样的东西

yahoo.com   2
gmail.com   1
4

1 回答 1

1

问题是您是按emailaddress不是 的值进行分组的domain。如果电子邮件地址包含john@yahoo.comor jim@yahoo.com,因为它们是唯一的,所以当您分组时,计数会将它们分开。

如果要按域值分组,则需要GROUP BY为域计算公式:

select SUBSTRING(EmailAddress, PATINDEX('%@%', EmailAddress) +1, LEN(EmailAddress) -PATINDEX('%@%', EmailAddress)) As [Domain], 
  COUNT(SUBSTRING(EmailAddress, PATINDEX('%@%', EmailAddress) +1, LEN(EmailAddress) - PATINDEX('%@%', EmailAddress))) As [Count]
from Subscribers
GROUP BY SUBSTRING(EmailAddress, PATINDEX('%@%', EmailAddress) +1, LEN(EmailAddress) -PATINDEX('%@%', EmailAddress));

或者您可以使用子查询然后按domain别名分组:

select domain,
  count(*) [count]
from
(
  select SUBSTRING(EmailAddress, PATINDEX('%@%', EmailAddress) +1, LEN(EmailAddress) -PATINDEX('%@%', EmailAddress)) As [Domain]
  from Subscribers
) d
group by domain;
于 2013-05-01T16:52:45.947 回答