views:

15

answers:

2

Finding Duplicate Row with Count Numbers

Suppose a table is given

  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 also should 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

For finding duplicates I can execute the query

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

How to generate the description?

+1  A: 

Try this -

select ID,Name,Age, ('Found ' +  cast(count(*) as varchar(5))) as description
from tableA  group by ID,Name,Age having count(*) >1 
Sachin Shanbhag
+1  A: 
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
gbn