Compare each records of same table in sql server and return duplicates

那年仲夏 提交于 2019-12-01 23:07:46

You can use a join to search for other identical rows. A join tries to match all rows from the right hand table based on the on condition. For example:

select  *
from    YourTable t1
join    YourTable t2
on      t1.ID < t2.ID -- Must be different rows
                      -- Smaller than presents the duplicates once
                      -- Otherwise you'd get both 1,3 and 3,1
        and abs(datediff(day, t1.date2, t2.date2)) <= 10
        and abs(datediff(day, t1.date4, t2.date4)) <= 10
        and t1.Number = t2.Number
        and t1.Code = t2.Code
        and -- So on for every column that should be equal

To ignore a column, omit it from the on condition.

This is how I solved this. Thanks for help.

select t1.Number,t1.Code,t1.Type,t1.date1,t1.Date2,t1.date3,t1.Date4,t1.stats,t1.shortn‌​ame,t1.CP, t1.deferred 
from T t1 join T t2 on 1=1 and t2.Number = t1.Number and t2.Code = t1.Code and t2.Type = t1.Type and t2.deferred = t1.eferred and t2.CP = t1.CP and t2.status = t1.status and abs(datediff(day,t1.Date2,t2.Date2)) <=10 and abs(datediff(day,t1.date3,t2.date3)) <=10 and abs(datediff(day,t1.Date4,t2.Date4)) <=10 group by t1.Number, t1.Code,t1.Type , t1.date1, t1.Date2,t1.date3,t1.Date4 ,t1.status,t1.shortname,t1.CP, t1.deferred having count(*) > 1
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!