【问题标题】:How to show only rows where there is no match between strings at all?如何仅显示字符串之间根本不匹配的行?
【发布时间】:2021-04-16 05:18:43
【问题描述】:

我必须比较两列,并且只能提取字符串之间甚至没有部分匹配的行。比如我有这张表:

Col1 Col2
John Smith John Smith ltd
Pepper Row Whatever Pepper
red Blue

过滤后我应该看到的唯一一行是最后一行:

Col1 Col2
red Blue

我找到了一个答案here,它显示了部分匹配的结果。我尝试使用NOT LIKE 将其修改为仅返回 0 个匹配项,但没有成功。

【问题讨论】:

  • 'Blue' 和 'Red' 都有字母'e',为什么不是“匹配”?什么是匹配,什么不是?如果一个是'John Smith ltd' 而另一个是'Jane Grey Limited' 你会期望'ltd''Limited' 匹配吗?
  • 匹配是整个单词,而不是单个字母。我不指望有限公司。并且仅限于匹配。
  • 一个单词的缩写不算匹配?您可以在其中添加标点符号,例如.,'Jane Smith's'John Smith' 之类的呢?他们都是'Smith'
  • 嗯,我提供的链接将显示诸如您的示例之类的行,我会看到这些是不同的公司。并将评估该怎么做。但在我的情况下,我要么有类似'John Smith''John Smith Ltd' 的相似性,要么有完全不同的类似:'Apple inc''Pear ltd'。我想展示后者,因为在我的情况下,它会指出更新不起作用的地方。

标签: sql sql-server string-matching


【解决方案1】:

如果您想要没有单词重叠的行,您可以使用not exists 子句:

select t.*
from t
where not exists (select 1
                  from string_split(t.col1, ' ') s1 join
                       string_split(t.col2, ' ') s2
                       on s1.value = s2.value
                 );

注意:此公式允许您返回整行 - 即未包含在比较中的其他列。

如果您使用的是不支持 string_split() 的旧版本 SQL Server,我建议您查找执行相同操作的用户定义函数的代码。

【讨论】:

    【解决方案2】:

    如果您只想拆分 col1 单词并想检查它是否存在于 col2 中,您可以尝试如下。

    select col1,col2 from mytable
    except   
    select col1,col2 from mytable t
    cross apply
    (
     select * from string_split(t.Col1,' ')
    )x    
    where col2  like  '%' + [value] + '%'  
    

    注意string_split 适用于 SQL Server 2017+,如果您使用的是旧版本,则需要使用一些自定义拆分功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-16
      • 2014-08-14
      • 1970-01-01
      • 2013-04-26
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      相关资源
      最近更新 更多