需要用逗号分割列,并需要在SQL中对列进行分组

时间:2016-01-08 11:45:06

标签: sql-server

我有一个表作为DepartmentDoc。

   Name           departmentDoc    UploadCount
   -----          ----------       ---------
   Surya             IT              4
   Surya,Kavi        IT              2
   Vijay,Kavi        Sales           2
   Vijay,Surya,Kavi  Purchase        1
   Swathi            Purchase        2

我想拆分包含','的字符串。然后我需要分组名称。我的输出选择查询将执行以下操作,

1)需要溢出名称列值,其中包含',' 2)在拆分文本后,我们需要将名称与新行分开,并为所有用户单独提供相同的上传计数。

我的输出应该是,

   Name           departmentDoc    UploadCount
   -----          ----------       ---------
   Surya             IT              4
   Surya             IT              2
   Kavi              IT              2
   Vijay             Sales           2
   Kavi              Sales           2
   Vijay             Purchase        1
   Surya             Purchase        1
   Kavi              Purchase        1
   Swathi            Purchase        2

我不知道如何在SQL Server中添加逗号添加文本并为分割文本创建新行。请帮帮我。谢谢。

3 个答案:

答案 0 :(得分:1)

DECLARE @Table1 TABLE 
    ( Name  varchar(16),  departmentDoc  varchar(8),  UploadCount  int)
;

INSERT INTO @Table1
    ( Name ,  departmentDoc ,  UploadCount )
VALUES
    ('Surya', 'IT', 4),
    ('Surya,Kavi', 'IT', 2),
    ('Vijay,Kavi', 'Sales', 2),
    ('Vijay,Surya,Kavi', 'Purchase', 1),
    ('Swathi', 'Purchase', 2)
;


;with cte as (
SELECT   
     Split.a.value('.', 'VARCHAR(100)') AS Name  ,departmentDoc, UploadCount
 FROM  (SELECT   
         CAST ('<M>' + REPLACE([Name], ',', '</M><M>') + '</M>' AS XML) AS String ,departmentDoc, UploadCount
     FROM  @Table1) AS A CROSS APPLY String.nodes ('/M') AS Split(a))


select * from CTE

答案 1 :(得分:0)

DECLARE @t TABLE (
    Name VARCHAR(100),
    departmentDoc VARCHAR(20),
    UploadCount INT
)

INSERT INTO @t (Name, departmentDoc, UploadCount)
VALUES
    ('Surya' , 'IT', 4),
    ('Surya,Kavi' , 'IT', 2),
    ('Vijay,Kavi ' , 'Sales', 2),
    ('Vijay,Surya,Kavi' , 'Purchase', 1),
    ('Swathi' , 'Purchase', 2)

SELECT O.Name,
       t.departmentDoc,
       t.UploadCount
FROM (
    SELECT *, x = CAST('<X>' + REPLACE(Name, ',', '</X><X>') + '</X>' AS XML)
    FROM @t
) t
CROSS APPLY (
    SELECT Name = t.c.value('.', 'VARCHAR(50)')
    FROM x.nodes('X') t(c)
) O

输出 -

Name         departmentDoc        UploadCount
------------ -------------------- -----------
Surya        IT                   4
Surya        IT                   2
Kavi         IT                   2
Vijay        Sales                2
Kavi         Sales                2
Vijay        Purchase             1
Surya        Purchase             1
Kavi         Purchase             1
Swathi       Purchase             2

答案 2 :(得分:0)

您可以使用字符串拆分功能执行此操作,例如Jeff Moden的DelimitedSplait8k。这样您就不必担心有任何可能破坏数据中XML函数的事情。

示例:

select
S.Item,
T.departmentDoc,
T.UploadCount
from table1 T
cross apply DelimitedSplit8K(Name, ',') S

SQL Fiddle

中的示例