繁体   English   中英

如何在DB2或SQL Server中找到两个表的行中的差异

[英]How to find difference in rows for two tables in DB2 or SQL Server

在table1中,我有1421144行,而table2有1421134行。

我尝试了此查询,但是没有返回任何行。

select table1.ID 
from table1
where ID not in (select ID from table2)

我还使用了以下查询:

select ID from table1
except
select ID from table2

但是我没有任何行。 请帮助我,如果table1有重复项,如何获得这些重复项?

假设ID是唯一的,则可以在两个数据库中使用full outer join

select coalesce(t1.id, t2.id) as id,
       (case when t1.id is null then 'T2 only' else 'T1 only' end) 
from t1 full outer join
     t2
     on t1.id = t2.id
where t1.id is null or t2.id is null;

这两个表很可能具有相同的ID集,但是有重复项。 尝试这个:

select t1.id, count(*)
from t1
group by t1.id
having count(*) > 1;

select t2.id, count(*)
from t2
group by t2.id
having count(*) > 1;

如果重复,请尝试:

WITH Dups AS(
    SELECT ID, COUNT(ID) OVER (PARTITION BY ID) AS DupCount
    FROM Table1)
SELECT *
FROM Dups
WHERE DupCount > 1;

如果需要删除公片,则可以使用以下语法:

WITH Dups AS(
    SELECT ID, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) AS DupCount
    FROM Table1)
DELETE FROM Dups
WHERE DupCount > 1;

但是,显然,在运行从Internet上的随机数据获取的DELETE语句之前,请检查数据。 ;)

我猜你有两个表之间的数据类型不匹配,将它们转换为整数,然后尝试您的第一个查询

select table1.ID from table1
where cast(ID as int) not in (select cast(ID as int) from table2)

如果您使用的存储格式与int不同,则将其转换为varchar并尝试使用此数据类型。

Not in执行需要较长时间,请改用左联接

select t1id from 
(
select t1.id t1Id, t2.Id t2Id from  table1 left join table2
on cast(t1.id as int) = cast(t2.id as int) 
) x where t2Id is null 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM