Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all duplicate records in SQL table with Entity Framework

I want to create a datagrid which contains all the records with then same name.

I have this table:

Shop
ID name          adress            city
-----------------------------------------
1  name1         adress 1          city1
2  name 2        adress2           city2
3  name 2        
4  name 2                          city2
5  name 3        
6  name 4        adress4           city4
7  name 4        adress4           city4

and my datagrid must contain:

2  name 2        adress2           city2
3  name 2        
4  name 2                          city2
6  name 4        adress4           city4
7  name 4        adress4           city4

but I have no idea how to create this query

like image 530
Fabrice Mainguené Avatar asked Sep 23 '13 09:09

Fabrice Mainguené


People also ask

How do I find duplicate names in a table in SQL?

To find the duplicate Names in the table, we have to follow these steps: Defining the criteria: At first, you need to define the criteria for finding the duplicate Names. You might want to search in a single column or more than that. Write the query: Then simply write the query to find the duplicate Names.


2 Answers

If you use Entity Framework I assume you use LINQ as well.

In which case, try it this way:

var duplicates = Shop.GroupBy(i => i.Name)
                     .Where(x => x.Count() > 1)
                     .Select(val => val.Key);

foreach(var item in duplicates)
{
    //process
}

In a simple example the output would look like this: Linqpad example

//EDIT:

if you want to group by multiple columns you can use this syntax:

var query = (from sh in Shop
     group sh by new {sh.Name, sh.Address, sh.City} into grp
     select new
     {
        name = grp.Key.Name,
        address = grp.Key.Address,
        city = grp.Key.City
     }).ToList()
       .GroupBy(q => q.name)
       .Where (q => q.Count() >1)
       .Dump();

This will result in the following:

second result

//EDIT2: sometimes I am borderline stupid. Following the KISS-principle:

var query = Shop.GroupBy (s => s.Name).Where (s => s.Count () > 1).Dump();
like image 146
Marco Avatar answered Oct 10 '22 18:10

Marco


Try this way:

select name, adress, city
from tab
where name in ( select name
                from tab
                group by name
                having count(name) >1 )
like image 42
Robert Avatar answered Oct 10 '22 19:10

Robert