在两个表之间查找重复值

时间:2018-10-09 17:21:34

标签: sql sql-server database

我有两个表:Customer1Customer2。两个表的字段相同,但员工名称不同。在两个表中都重复了一些员工。

我想找到在两个表中都重复的员工。

样本数据:

Customer 1

    ID  Name     Designation  salary
    1   User1     Developer    5000
    1   User2     Developer    5000
    1   User5     Developer    5000
    1   User1     Developer    5000


Customer 2

    ID  Name     Designation  salary
    1   User1     Developer    5000
    1   User2     Developer    5000
    1   User3     Developer    5000
    1   User1     Developer    5000

Result

    ID  Name     Designation  salary
    1   User1     Developer    5000
    1   User2     Developer    5000

User1User2在这两个表中都有很多次,但是我只想计算一次。我对此表示感谢。

2 个答案:

答案 0 :(得分:1)

您可以将两个表连接起来,并打印出Customer1中剩下的不同记录:

SELECT distinct customer1.*
FROM customer1 
    INNER JOIN customer2 ON
        customer1.id = customer2.id 
        AND customer1.name = customer2.name

答案 1 :(得分:1)

您可以使用UNION ALL并进行夸张:

select id, name, Designation, salary
from (select c1.id, c1.name, c1.Designation, c1.salary
      from Customer1 c1
      union all
      select c2.id, c2.name, c2.Designation, c2.salary
      from Customer2 c2
     ) c
group by id, name, Designation, salary
having count(*) > 1;