SQL找到多个字段无与伦比的

时间:2016-10-05 12:05:06

标签: sql sql-server

我正在寻找一种从多个字段中查找不匹配记录并返回结果进行比较的方法。

例如

T1

ID    Name    Surname   Status
1     Jane    Ryan      Single
2     William Smith     Single
3     Sam     Trim      Married
4     Lea     Sun       Married
5     Angel   Byre      Married

T2

ID    Name    Surname   Status
6     Jane    Ryan      Single
2     Will    Smith     Single
3     Sam     Trimy     Married
4     Lea     Sun       Single
5     Angel   Byre      Married

我想要显示如下内容:

T1.ID T1.Name T1.Surname T1.Status T2.ID T2.Name T2.Surname T2.Status
1     Jane    Ryan       Single    6     Jane    Ryan       Single
2     William Smith      Single    2     Will    Smith      Single
3     Sam     Trim       Married   3     Sam     Trimy      Married
4     Lea     Sun        Married   4     Lea     Sun        Single

第5条记录未显示,因为它完全相同。显示其他字段是其中一个字段。

有没有办法做到这一点是MS-SQL

由于

3 个答案:

答案 0 :(得分:3)

您可以使用所有字段的联接,并计算其中有多少匹配,只保留四个字段中恰好三个匹配的记录:

select     t1.*, 
           t2.*
from       t1 
inner join t2
        on (case when t1.name    = t2.name    then 1 else 0 end)
         + (case when t1.surname = t2.surname then 1 else 0 end)
         + (case when t1.id      = t2.id      then 1 else 0 end)
         + (case when t1.status  = t2.status  then 1 else 0 end) = 3

此查询可能无法从索引中受益,因此您应该验证它对数据的执行情况。

答案 1 :(得分:0)

您可以使用join

执行此操作
select t1.*, t2.*
from t1 join
     t2
     on (t1.name = t2.name and t1.surname = t2.surname) or
        t1.id = t2.id 
where t1.id <> t2.id or t1.status <> t2.status or
      t1.name <> t2.name or t1.surname <> t2.name;

答案 2 :(得分:0)

将列别名用于同义词

SELECT T1.ID AS [T1.ID]
    ,T1.NAME AS [T1.Name]
    ,T1.Surname AS [T1.Surname]
    ,T1.STATUS AS [T1.Status]
    ,T2.ID AS [T2.ID]
    ,T2.NAME AS [T2.Name]
    ,T2.Surname AS [T2.Surname] 
    ,T2.STATUS AS  [T2.Status]
FROM T1
INNER JOIN T2 ON T1.NAME = T2.NAME
    AND T1.Surname = T2.Surname
    AND T1.ID <> T2.ID
    AND T1.STATUS <> T2.STATUS