开发者

Find duplicate row "details" in table

OrderId  OrderCode  Description
-------------------------------
1        Z123       Stuff
2        ABC999     Things
3        Z123       Stuff

I have duplicates in a table like the above. I'm trying to get a report of which Orders are duplicates, and what Order they are duplicates of, so I can figure out how they 开发者_如何学运维got into the database.

So ideally I'd like to get an output something like;

OrderId    IsDuplicatedBy
-------------------------
1          3
3          1

I can't work out how to code this in SQL.


You can use the same table twice in one query and join on the fields you need to check against. T1.OrderID <> T2.OrderID is needed to not find a duplicate for the same row.

declare @T table (OrderID int, OrderCode varchar(10), Description varchar(50))
insert into @T values
(1, 'Z123', 'Stuff'),
(2, 'ABC999', 'Things'),
(3, 'Z123', 'Stuff')

select
  T1.OrderID,
  T2.OrderID as IsDuplicatedBy
from @T as T1
  inner join @T as T2
    on T1.OrderCode = T2.OrderCode and
       T1.Description = T2.Description and
       T1.OrderID <> T2.OrderID

Result:

OrderID IsDuplicatedBy
1   3
3   1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜