Group by sql query on comma joined column

后端 未结 6 1301
孤独总比滥情好
孤独总比滥情好 2020-12-10 22:57

My table structure is like below, "Mail" column can contain multiple email joined by comma

Data(int)

Mail(v

6条回答
  •  抹茶落季
    2020-12-10 23:23

    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

    • #tmp: your table name
    • #mail: the column name

提交回复
热议问题