[SalesForce] Get List of Accounts of duplicate Contacts

Requirement:

A component that displays duplicate Contacts (having the same Name) along with the Account each of those Contacts is linked to.

Here is my current query:

[SELECT Name, count(Id), Account.Name FROM Contact GROUP BY Name HAVING count(Id)>1];

Basically, it's using an aggregate function to find the duplicate Contacts and then traversing to Account.Name in the query

But this isn't working. Error message in console:

duplicate alias: Name

I suspect this is because the parser can't distinguish between the Contact.Name and the Account.Name field in our query. Since, according my understanding, using AS isn't possible for fields, only for tables in SOQL, I'm at the end of my latin.

Anybody has an idea how to resolve this?

Best Answer

You are getting that error because you are selecting Account.Name field without grouping it. You either have to group it or you have to aggregate it.

So basically, this below code should suffice your needs

Set<string> setNames = new Set<string>();
for(AggregateResult ar : [SELECT  Name, count(Id) ContactCount FROM Contact GROUP BY Name HAVING count(Id)>1]){
    setNames.add(string.valueOf(ar.get('Name')));
}

List<Contact> dupContacts = [SELECT Id, Name, Account.Name FROM Contact WHERE Name IN :setNames order by Name];