删除字符串sql表中的重复值

时间:2015-07-15 22:23:35

标签: sql sql-server excel

我有一个值为

的表格
ID Names     
1  Adam,eve,adam,rick 
2  Don,jack,rick,don 

需要删除名称列的重复值:out put应该类似于以下

1 Adam,Eve, Rick
2 Don Jack,Rick 

3 个答案:

答案 0 :(得分:0)

您可以使用拆分器功能执行此操作。这是一张取自Aaron Bertrand的article.

CREATE FUNCTION dbo.SplitStrings_XML
(
   @List       NVARCHAR(MAX),
   @Delimiter  NVARCHAR(255)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
   RETURN 
   (  
      SELECT Item = y.i.value('(./text())[1]', 'nvarchar(4000)')
      FROM 
      ( 
        SELECT x = CONVERT(XML, '<i>' 
          + REPLACE(@List, @Delimiter, '</i><i>') 
          + '</i>').query('.')
      ) AS a CROSS APPLY x.nodes('i') AS y(i)
   );

然后,您的最终查询将是:

SQL Fiddle

SELECT *
FROM @tbl t
CROSS APPLY(
    SELECT STUFF((
        SELECT DISTINCT ',' + Item
        FROM dbo.SplitStrings_XML(t.Names, ',')
        FOR XML PATH('')
    ), 1, 1, '')
)x(Item)

<强> RESULT

| ID |                       Names |                  Item |
|----|-----------------------------|-----------------------|
|  1 |          Adam,eve,adam,rick |         Adam,eve,rick |
|  2 | Hello,World,Something,Hello | Hello,Something,World |

答案 1 :(得分:0)

数据库数据是表格式的,您需要从这种方法中移除,每行只保存一个名称,您只需按名称进行编制并添加计数,计数中包含多个名称的任何名称都是重复的,然后使用最大或一分钟,以获取您要删除作为删除语句源的用途的ID。

答案 2 :(得分:0)

通过使用简单的Stuff Function和Split我们可以实现这个

 declare @t table (Id int,value varchar(50))
    insert into @t (Id,value)
    values 
    (1,'Adam,eve,adam,rick'),
    (2,'Don,jack,rick,don')
    ;with cte as (
    SELECT ID,  
         Split.a.value('.', 'VARCHAR(100)') AS String  
     FROM  (SELECT ID,  
             CAST ('<M>' + REPLACE([value], ',', '</M><M>') + '</M>' AS XML) AS String  
         FROM  @t) AS A CROSS APPLY String.nodes ('/M') AS Split(a))

         Select DISTINCT  C.ID,
         STUFF((select DISTINCT +','+ string 
            from cte where ID = C.ID 
         GROUP BY ID,string FOR XML PATH(''))
        , 1, 1, '')Val from cte C GROUP BY C.ID,C.string