Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query for finding duplicates

I am having a table with following schema:

CUSTOMERS (id INT, name VARCHAR(10), height VARCHAR(10), weight INT)

id is the primary key. I want to find out rows in which people who are having exactly same name, same height and same weight. In other words, I want to find out duplicates with-respect-to name, height and weight.

Example table:

1, sam, 160, 100
2, ron, 167, 88
3, john, 150, 90
4, sam, 160, 100
5, rick, 158, 110
6, john, 150, 90
7, sam, 166, 110

Example Output:

Now since there are people with same name, same height and same weight:

sam (id=1), sam (id=4)

and

john (id=3), john (id=6)

I want to get these ids. It is also okay if I get only one id per match (i.e. id=1 from first match and id=3 from second match).


I am trying this query but not sure if it is correct or not.

SELECT id
FROM customers
GROUP BY name, height, weight
like image 726
sumit Avatar asked Jan 20 '26 23:01

sumit


1 Answers

Try this (valid for sql server):

SELECT 
    t.NAME,
    'Ids = '+
    (
        SELECT cast(Id as varchar)+',' 
        FROM Customers c 
        WHERE c.NAME = t.NAME AND c.Weight = t.Weight AND c.Height = t.Height
        FOR XML PATH('')
    )
FROM
(
    SELECT Name, height, weight
    FROM Customers
    GROUP BY Name, height, weight
    HAVING COUNT(*) > 1
) t

OR

as you asked - only one Id per match

SELECT 
    t.NAME,
    c.Id
FROM
(
    SELECT Name, height, weight
    FROM Customers
    GROUP BY Name, height, weight
    HAVING COUNT(*) > 1
) t
JOIN Customers c ON t.NAME AND c.Weight = t.Weight AND c.Height = t.Height
like image 67
Oleg Dok Avatar answered Jan 22 '26 12:01

Oleg Dok