You need to sign in to do that
Don't have an account?
Egui
Get accounts with only one contact
Hello,
I'm struggling to write an SOQL query to get all contacts which are alone on their account.
In other words get all accounts with only one contact and get those contacts.
Help would be very welcome.
Thanks !
Consult the HAVING section of your SOQL SOSL Handbook. I believe you'd have to do this in two parts though since the HAVING clause doesn't allow you to do semi-joins or anti-joins.... but your query would look something like:
Set<Id> singleContacts = new Set<Id>();
for(Contact c : [select AccountId, COUNT(Id) FROM Contact GROUP BY AccountId HAVING COUNT(Id) = 1]){
singleContacts.add(c.AccountId);
}
for(Contact c : [select Id, AccountId, (all the other fields you want) FROM Contact WHERE AccountId IN: singleContacts]){
//Do what you want to do to all the contacts who are the only contact on their respective accounts.
}
All Answers
Consult the HAVING section of your SOQL SOSL Handbook. I believe you'd have to do this in two parts though since the HAVING clause doesn't allow you to do semi-joins or anti-joins.... but your query would look something like:
Set<Id> singleContacts = new Set<Id>();
for(Contact c : [select AccountId, COUNT(Id) FROM Contact GROUP BY AccountId HAVING COUNT(Id) = 1]){
singleContacts.add(c.AccountId);
}
for(Contact c : [select Id, AccountId, (all the other fields you want) FROM Contact WHERE AccountId IN: singleContacts]){
//Do what you want to do to all the contacts who are the only contact on their respective accounts.
}
hi,