简体   繁体   English

如何在T-SQL中拆分逗号分隔的重复字符串

[英]How to split repeating string delimated by commas in T-SQL

I have tried some trials and can't figure it out yet. 我已经尝试过一些试验,但还不能解决。 Any help would be appreciated. 任何帮助,将不胜感激。

I have a table like below. 我有一张下面的桌子。

LocationID       Project Name
1                A,A
1                A
1                A,B,C
1                A,C
1                B,C
1                C
2                A
2                C,D,E
2                E,F
2                F
3                G,H
3                H

The result I am looking for is. 我正在寻找的结果是。 It removes all the repeatings and keep only distinct values with their associated ID. 它会删除所有重复项,并仅保留具有其关联ID的不同值。

LocationID       Project Name
1                A
1                B
1                C
2                A
2                C
2                D
2                E
2                F
3                G
3                H

I tried to count the number of commas by (len(replace(@ProjectNames, ',')) 我试图用(len(replace(@ProjectNames,','))来计算逗号的数量

Using split function from http://www.logiclabz.com/sql-server/split-function-in-sql-server-to-break-comma-separated-strings-into-table.aspx 使用http://www.logiclabz.com/sql-server/split-function-in-sql-server-to-break-comma-separated-strings-into-table.aspx中的拆分功能

However, still no luck.. Any help would be appreciated. 但是,仍然没有运气。任何帮助将不胜感激。 Thank you. 谢谢。

declare @T table(LocationID int, PName varchar(50))

insert into @T values
(1,                'A,A'),
(1,                'A'),
(1,                'A,B,C'),
(1,                'A,C'),
(1,                'B,C'),
(1,                'C'),
(2,                'A'),
(2,                'C,D,E'),
(2,                'E,F'),
(2,                'F'),
(3,                'G,H'),
(3,                'H')

select distinct
  T.LocationID,
  r.value('.', 'varchar(50)') as [Project Name]
from @T as T
  cross apply
    (select cast('<r>'+replace(PName, ',', '</r><r>')+'</r>' as xml)) as x(x)
  cross apply
    x.nodes('r') as r(r)

try select distinct . 尝试选择不同的。

if you use mysql , you can use group_concat() function to regroup the distinct values. 如果使用mysql,则可以使用group_concat()函数重新组合不同的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM