TSQL Duplicate Search

Search for duplicate row with counter numbers

Suppose a table is defined

  ID  Name      Age
  ----------------- 
  1   Jon       30
  2   Skeet     30 
  1   Jon       30
  4   Gravell   30
  5   NULL      30 
  4   Gravell   30
  5   NULL      30 
  7   James     40 

Required output (NULL must also be comparable)

  ID  Name      Age  Description
  -----------------  -----------
  1   Jon       30      Found 1
  1   Jon       30      Found 2
  4   Gravell   30      Found 1
  4   Gravell   30      Found 2
  5   NULL      30      Found 1
  5   NULL      30      Found 2
  7   James     40      Found 1
  2   Skeet     30      Found 1

To search for duplicates, I can execute a query

select ID,Name,Age from tableA  group by ID,Name,Age having count(*) >1

How to generate a description?

+3
source share
2 answers
SELECT
    ID, Name, Age,
    'Found ' + CAST(ROWNUMBER() OVER (PARITION BY Name ORDER BY ID) AS varchar(10)) AS Description
FROM
    MyTable
ORDER BY
    ID, Description

Your desired output order is essentially random at the ID / Name level

To find duplicates ...

SELECT
    ID, Name, Age, 'Found ' + Countof AS Description
FROM
    (
    SELECT
        ID, Name, Age,
        CAST(ROWNUMBER() OVER (PARITION BY Name ORDER BY ID) AS varchar(10)) AS Countof
    FROM
        MyTable
    ) foo
WHERE
    Countof > 1
+1
source

Try it -

select ID,Name,Age, ('Found ' +  cast(count(*) as varchar(5))) as description
from tableA  group by ID,Name,Age having count(*) >1 
+1
source

Source: https://habr.com/ru/post/1763207/


All Articles