Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

How can I get the records which are deuplicated in a table?

Eg Table:

VB
ID | Name |Dept |Gender
=======================
1  |ABC   |DPT1 |M
2  |DEF   |DPT2 |M
3  |ABC   |DPT1 |F
4  |DEF   |DPT2 |F
5  |MNO   |DPT3 |M
6  |PQR   |DPT1 |M


Result:

VB
Name
====
ABC
DEF


Thanks,
Janes T
Posted

try this:-
SQL
SELECT name,Count(*) FROM Table_Name
GROUP BY name HAVING COUNT(*) > 1
 
Share this answer
 
v2
Comments
Kornfeld Eliyahu Peter 13-Jan-14 2:04am    
Not quit good. as no id, dept and gender are in the group by, it will result in error - you have to remove them...
Maciej Los 13-Jan-14 2:48am    
Corresponds to desired output.
+5!
Have a look at my answer.
SQL
SELECT Name,Dept,Gender
FROM tablename
GROUP BY Name,Dept,Gender
HAVING COUNT(*)>1
 
Share this answer
 
v2
Comments
Kornfeld Eliyahu Peter 13-Jan-14 2:08am    
Not quit good. as no id, dept and gender are in the group by, it will result in error - you have to remove them...
Maciej Los 13-Jan-14 2:46am    
What?
Kornfeld Eliyahu Peter 13-Jan-14 2:52am    
Column 'table_name.ID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Kornfeld Eliyahu Peter 13-Jan-14 2:53am    
When you have group by you must declare how to group every field in you select list - or aggregate it for every group - so KARTHIK's query will got a syntax error - see before
Maciej Los 13-Jan-14 2:58am    
OK, good point!
If you would like to get unigue names, you don't need any aggregate function. Use DISTINCT statement.

SQL
SELECT DISTINCT [name]
FROM TableName


If you would like to get duplicates only, aggregate function is necessary. See solution 1 by TrushnaK.
SQL
SELECT [name]
FROM TableName
GROUP BY [name]
HAVING COUNT([name])>1

But (!)... as you can see, you will get duplicate names, no matter of department and gender. I'm not sure you really want it.

SQL
SELECT [name], [gender], [dept]
FROM TableName
GROUP BY [name], [gender], [dept]
HAVING COUNT([name])>1
ORDER BY [name], [gender], [dept]


Above query returns names with its gender and place of employee hire.
 
Share this answer
 
You can use `EXISTS` like this:

SQL
SELECT DISTINCT Name
FROM t
WHERE EXISTS(
		SELECT 1 
		FROM t ti 
		WHERE ti.Name = t.Name AND ti.ID <> t.ID)


---

You can use `JOIN` like this:

SQL
SELECT DISTINCT t.Name
FROM t
    JOIN
    t ti ON t.Name = ti.Name AND t.ID <> ti.ID


---

You can use Inner-Select in `WHERE` like this:

SQL
SELECT DISTINCT t.Name
FROM t
WHERE
    1 < (SELECT COUNT(*) FROM t ti WHERE ti.Name = t.Name)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900