I have to query all the accounts where more than 1 contact with the field (primary = true). Let say, I have an Account and it has 3 contacts, 2 of contacts having a field(primary = true). So I have to fetch there 2 contacts only with Account. If I have 3 Contacts and 1 contact of them having a field(primary =true) this contact I don't want to get. Please let me know the SOQL query for this.
The best way to approach this kind of query - locating parent objects by count and attribute of their children - is often an aggregate query. The skeleton would look something like this:
SELECT count(Id), AccountId FROM Contact WHERE Primary = true GROUP BY AccountId HAVING count(Id) > 1
You can execute this query in the developer console, or assign it to a
List<AggregateResult> in Apex and loop over those records to process them.