How get the T-SQL code to find duplicates?

前端 未结 5 613
清酒与你
清酒与你 2020-12-12 20:36

MS Access has a button to generate sql code for finding duplicated rows. I don\'t know if SQL Server 2005/2008 Managment Studio has this.

  1. If it has, please

5条回答
  •  一向
    一向 (楼主)
    2020-12-12 21:01

    Another way one can do this is by joining a table on itself.

    SELECT *
    FROM dbo.TableA aBase
    JOIN dbo.TableA aDupes ON aDupes.ColA = aBase.ColA AND
                              aDupes.ColB = aBase.ColB
    WHERE aBase.Pkey < aDupes.Pkey
    

    Note: The aBase.Pkey < aDupes.Pkey is there because joining a table against itself will create two rows per match since the condition will always be true twice.

    In other words: If table aBase has a row equal to a row from aDupes (based on ColA and ColB), the reflection of that match will also be true - that aDupes has a row equal to a row aBase based on ColA and ColB. Therefore both of those matches will be returned in the result set.

    Narrow this down/eliminate this reflection by arbitrarily picking all results where one of the tables has a lower key.

    < or > doesn't matter, as long as the keys are different.

    This also takes care of filtering out matches with a row upon itself because aBase.Pkey < aDupes.Pkey forces the primary keys to be different.

提交回复
热议问题