从SQL Server中的表中拆分逗号分隔值

时间:2014-05-01 13:10:01

标签: sql sql-server sql-server-2008 sql-server-2012

我有一个SQL table,其中包含许多记录,我想知道其中有多少个名称以及其中一个名称的时间。

表NameMst

Name

john,smith,alax,rock
smith,alax,sira
john,rock
rock,sira

我想知道有多少名字和数量。

预期输出应该是这样的

Name           Count

john           2
smith          2
alax           2
rock           3
sira           2

帮我解决。

3 个答案:

答案 0 :(得分:2)

您可以使用递归CTE和一些字符串解析来提取名称。其余的只是聚合:

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;

正如您可能已经想到的那样,在SQL Server中存储以逗号分隔的列表是个坏主意。您应该有一个关联/联结表,每个名称一行(以及描述其所在列表的其他列)。

答案 1 :(得分:1)

SELECT y.Name, count(*) Count
FROM
(VALUES
('john,smith,alax,rock'),
('smith,alax,sira'),
('john,rock'),
('rock,sira')) x(names)
CROSS APPLY
(
SELECT t.c.value('.', 'VARCHAR(2000)') Name
     FROM (
         SELECT x = CAST('<t>' + 
               REPLACE(x.names, ',', '</t><t>') + '</t>' AS XML)
     ) a
     CROSS APPLY x.nodes('/t') t(c)
     ) y
GROUP BY y.Name

结果:

Name   Count
alax   2
john   2
rock   3
sira   2
smith  2

答案 2 :(得分:0)

DECLARE @table1 TABLE ( id VARCHAR(50) )
DECLARE @table TABLE ( id1 INT,id VARCHAR(50) )
INSERT INTO @table (id1,id) values (1, 'JOHN,rom')
INSERT INTO @table (id1,id) values (2,'Micky,Raju')
INSERT INTO @table (id1,id) values (2,'Micky,Raju')
INSERT INTO @table (id1,id) values (2,'Micky,Raju')
DECLARE @Min INT,@Max INT ,@str1 VARCHAR(100),@str2 VARCHAR(100)

DECLARE @x INT = 0
DECLARE @firstcomma INT = 0
DECLARE @nextcomma INT = 0

SELECT @x =   LEN(id) - LEN(REPLACE(id, ',', '')) + 1 from @table -- number of ids in id_list

WHILE @x > 0
    BEGIN
        SELECT @nextcomma =  CASE WHEN CHARINDEX(',', id, @firstcomma + 1) = 0
                              THEN LEN(id) + 1
                              ELSE CHARINDEX(',', id, @firstcomma - 1)
                         END FROM @table
                         --select @nextcomma
        INSERT  INTO @table1
        SELECT  ( SUBSTRING(id, @firstcomma + 1, (@nextcomma - @firstcomma) - 1) ) FROM @table 
        SELECT @firstcomma = CHARINDEX(',', id, @firstcomma + 1)FROM @table
        SET @x = @x - 1
    END

SELECT  DISTINCT id,COUNT(id)
FROM    @table1
GROUP BY id