My table structure is like below, "Mail" column can contain multiple email joined by comma
Data(int)
Mail(v
String splitting is faster using only CHARINDEX without XML or CTE.
Sample table
create table #tmp ([Data] int, [Mail] varchar(200))
insert #tmp SELECT 1,'m1@gmail.com,m2@hotmail.com,other, longer@test, fifth'
UNION ALL SELECT 2,'m2@hotmail.com,m3@test.com'
UNION ALL SELECT 3,'m3@single.com'
UNION ALL SELECT 4,''
UNION ALL SELECT 5,null
The query
select single, count(*) [Count]
from
(
select ltrim(rtrim(substring(t.mail, v.number+1,
isnull(nullif(charindex(',',t.mail,v.number+1),0)-v.number-1,200)))) single
from #tmp t
inner join master..spt_values v on v.type='p'
and v.number <= len(t.Mail)
and (substring(t.mail,v.number,1) = ',' or v.number=0)
) X
group by single
The only parts you supply are