split comma seprate value from table in sql server

前端 未结 3 1173
迷失自我
迷失自我 2021-01-25 10:21

i have one SQL table in which many records, i want to know how many names are in it and how much time one name in it.

Table NameMst

Name

jo         


        
3条回答
  •  我在风中等你
    2021-01-25 10:57

    You can extract the names using a recursive CTE and some string parsing. The rest is just aggregation:

    with cte as (
          select (case when names like '%,%'
                       then left(names, charindex(',', names) - 1)
                       else names
                  end) as name,
                 (case when names like '%,%'
                       then substring(names, charindex(',', names) + 1, len(names))
                  end) as names
          from names
          union all
          select (case when names like '%,%'
                       then left(names, charindex(',', names) - 1)
                       else names
                  end) as name,
                 (case when names like '%,%'
                       then substring(names, charindex(',', names) + 1, len(names))
                  end)
          from cte
          where names is not null
         )
    select name, count(*)
    from cte
    group by name;
    

    As you have probably figured out, storing comma delimited lists in SQL Server is a bad idea. You should have an association/junction table with one row per name (and other columns describing the list it is in).

提交回复
热议问题