我有一个包含电子邮件地址和帐号的表格(以及其他数据)。
为了简化,我删除了其他数据。
123456, joe@place.com
123457, phil@place.com
123456, jil@place.com
123456, jane@place.com
123458, john@place.com
根据上面的示例,大多数帐户都有多个电子邮件地址。
我需要创建一个查询来告诉我:
答案 0 :(得分:3)
内部查询(q
)将计算每个帐户拥有的不同电子邮件地址的数量。然后外部查询将计算每个计数桶中有多少帐户(1,2,3,...)。
SELECT q.email_counter, COUNT(*) AS num_accounts
FROM (SELECT account_number,
COUNT(DISTINCT email_address) AS email_counter
FROM YourTable
GROUP BY account_number) q
GROUP BY q.email_counter;
答案 1 :(得分:2)
您可以使用
select acc_no, count(*) from your_table group by acc_no
答案 2 :(得分:1)
你可以试试这个:
select accountnumbers, count(*)
from yourtablename
group by accountnumbers
答案 3 :(得分:0)
您可以使用条件聚合来获得所需的旋转结果集:
SELECT COUNT(CASE WHEN cnt = 1 THEN 1 END) AS cnt1,
COUNT(CASE WHEN cnt = 2 THEN 1 END) AS cnt2,
COUNT(CASE WHEN cnt = 3 THEN 1 END) AS cnt3,
....
FROM (
SELECT COUNT(*) AS cnt, accountId
FROM accounts
GROUP BY accountId ) t
cnt1
包含拥有1封电子邮件的帐户ID数量,cnt2
包含2封电子邮件的帐户ID数量等。
答案 4 :(得分:0)
已经有了很好的答案,但是我只是想通过条款回答添加一个组:
declare @intDesiredCount int = 2 --or 3 or 4 or 10
select AccountNumber
, Count(1) as EmailAddressCount
from ContactTable
Group by AccountNumber
having Count(1) = @intDesiredCount
对帖子聚合值进行过滤,在此示例中为电子邮件地址的数量。