【问题标题】:SQL find value in one table in another variationSQL 在另一个变体中的一个表中查找值
【发布时间】:2018-04-12 19:36:51
【问题描述】:

我有两张这样的桌子。

Table1
FullName     LastName    FirstName
John Smith   Smith       John

Table2
LastName     Firstname   AKA
Smith Stein  Johnny      John the Bad Guy

我需要在table2 中从table1 中找到lastnamefirstname 的任何变体。但是,我无法加入这些表,因为名称可能不同,所以没有什么可以加入的。基本上,我正在尝试将我们的列表与公共列表进行比较,以查看是否有任何名称匹配。

我正在尝试这个:

Select * 
from table1
where exists (select * 
    from table2 
    where charindex(table1.lastname, table2.lastname)>0 
        and charindex(table1.firstname,table2.firstname)>0)

我得到了返回值,但我也想查看 table2 中的值。

我需要查看 John Smith Returned 并显示 John Smith Stein 在另一张表中被标记。姓氏的这种变体也适用于名字。这就是为什么我不能加入任何 1 个特定列的原因。

对不起,如果这令人困惑。

【问题讨论】:

  • 请用您的数据库标记您的问题。
  • 您需要提供样本数据和期望的结果,这样其他人就有可能知道您正在尝试做什么。
  • 它的 SQL 2008 R2。我正在尝试弄清楚如何上传表格。

标签: sql sql-server-2008-r2 compare


【解决方案1】:

在您的示例中,您正在检查名称之间的完全匹配,那么为什么不加入它们呢?

SELECT t1.*, t2.*
FROM table1 t1
  JOIN table2 t2 on t2.firstname = t1.firstname
       and t2.lastname = t2.lastname

【讨论】:

  • 问题是名称不准确。如果名称 John Smith 在 table1 中,并且在 Table2 中我有 Johnny Smith Stein,我需要标记这个。这就是为什么我不能加入任何 2 列。
【解决方案2】:

不确定“相似”名称的规则是什么,但您可以尝试以下方法:

SELECT t1.*, t2.*
FROM table1 t1
  JOIN table2 t2 on  
        t1.lastname = t2.lastname or t1.lastname=t2.aka or whatever other rules you want to set up

【讨论】:

  • 您也可以尝试使用“差异”。返回的数字越高,字符串彼此越接近。看看这些查询: select difference('Jen R', 'Daniel Marcus') select difference('Dan Marcus', 'Daniel Marcus') select difference('Daniel Marcus', 'Daniel Marcus')
猜你喜欢
  • 1970-01-01
  • 2022-12-14
  • 2020-07-29
  • 2014-12-21
  • 1970-01-01
  • 2019-05-27
  • 2020-03-27
  • 2018-07-02
  • 2021-08-16
相关资源
最近更新 更多