select 使用计数查询

select query using count

我想统计拥有 gmail 或 yahoo 帐户的员工人数 结果应该是

email,         count
gmail.com      3
yahoo.com      2

到目前为止已经试过了

select count(emailid) 
from employee 
where emailid IN (select emailid from employee 
             WHERE emailid like '%@gmail.com' 
                  or select emailid from employee WHERE emailid like '%@yahoo.com')

试试这个

SELECT Substring (EmailId, Charindex( '@', EmailId ) + 1, Len(EmailId) )  , Count( EmpID)
FROM Emp
group by  Substring (EmailId, Charindex( '@', EmailId ) + 1, Len(EmailId) )

使用函数 Substring 获取邮箱后缀,然后按邮箱后缀分组

如果您有 gmail 和 yahoo 以外的电子邮件并且您只需要提到的电子邮件,请使用 where 子句

SELECT Substring (EmailId, Charindex( '@', EmailId ) + 1, Len(EmailId) )  , Count( EmpID)
FROM Emp
WHERE Substring (EmailId, Charindex( '@', EmailId ) + 1, Len(EmailId)) IN ('gmail.com','yahoo.com')
group by  Substring (EmailId, Charindex( '@', EmailId ) + 1, Len(EmailId) )
select SUBSTRING_INDEX(Email,'@',-1), count(*) Count
from employee 
where Email like '%gmail.com' or  email like '%yahoo.com'
group by  SUBSTRING_INDEX(Email,'@',-1)

如果您只需要计算 Gmail 和 yahoo 的电子邮件数量,也许更简单的解决方案应该是:

select count(*) as count,case when emailid like'%gmail%' then 'gmail.com' 
                              when emailid like'%yahoo%' then 'yahoo.com' end as email 
from employee
group by email;

演示:https://www.db-fiddle.com/f/7yUJcuMJPncBBnrExKbzYz/173

或者如果您只有 yahoo 或 Gmail 检查的电子邮件:

select count(*) as count,case when emailid like'%gmail%' 
                              then 'gmail.com' 
                              else 'yahoo.com' end as email 
from employee
group by email;

演示:https://www.db-fiddle.com/f/7yUJcuMJPncBBnrExKbzYz/172

Result:

count email
3     gmail.com
2     yahoo.com