sql server - Group by sql query on comma joined column -
my table structure below, "mail" column can contain multiple email joined comma
data(int)
mail(varchar(200))
[data] [mail]
1 m1@gmail.com,m2@hotmail.com
2 m2@hotmail.com,m3@test.com
& need generate report below, counting each row per each email
[mail] [count]
m1@gmail.com 1
m2@hotmail.com 2
m3@test.com 1
so sql(server) query generate above? can't change table structure.
string splitting faster using 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 select 2,'m2@hotmail.com,m3@test.com' union select 3,'m3@single.com' union select 4,'' union select 5,null
the query
select single, count(*) [count] ( select ltrim(rtrim(substring(t.mail, v.number+1, isnull(nullif(charindex(',',t.mail,v.number+1),0)-v.number-1,200)))) single #tmp t inner join master..spt_values v on v.type='p' , v.number <= len(t.mail) , (substring(t.mail,v.number,1) = ',' or v.number=0) ) x group single
the parts supply are
- #tmp: table name
- #mail: column name
Comments
Post a Comment