SQL Server - 匹配两列的多个字符串,并使用共享字符串列出记录

时间:2018-04-26 23:16:26

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

例如,我有这些数据:

ID  word1       word2
1   white dog   black dog
2   big tall    tall building
3   wood        green wood
4   big house   green wood
5   long way    street

我想列出具有相似字符串的两列:

ID  word1       word2
1   white dog   black dog
2   big tall    tall building
3   wood        green wood

我试过这个,但没有成功:

SELECT word1, word2 from  Table where word1 like '%'+word2+'%'

2 个答案:

答案 0 :(得分:0)

实际上任何分割/解析功能都可以。这是一种内联方法

示例

Select Distinct A.* 
 From  YourTable A
 Cross Apply (
                Select RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
                From  (Select x = Cast('<x>' + replace((Select replace(Word1,' ','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A 
                Cross Apply x.nodes('x') AS B(i)
             ) B
 Where charindex(' '+RetVal+' ',' '+Word2+' ')>0

<强>返回

ID  word1       word2
1   white dog   black dog
2   big tall    tall building
3   wood        green wood

答案 1 :(得分:0)

使用基于XML的拆分器的解决方案如下所示: See live demo

  SELECT 
        id,word1,word2
    FROM
     (
     SELECT 
      *,
      xmlwords1=cast('<X>'+replace(word1,' ','</X><X>')+'</X>' as XML),
      xmlwords2=cast('<X>'+replace(word2,' ','</X><X>')+'</X>' as XML)
     FROM 
         Sample
     )S1
     CROSS APPLY
     ( 
         SELECT 
             splitwordsfromWord1 = data1.D.value('.','varchar(100)'),
         splitwordsfromWord2 =data1.D.value('.','varchar(100)')
         FROM 
      S1.xmlwords1.nodes('X') AS data1(D)
         JOIN
      S1.xmlwords2.nodes('X') AS data2(D)
         ON
            data1.D.value('.','varchar(100)')= data2.D.value('.','varchar(100)')
      ) O