0

I have a list with records from Policy__c which is a custom object.

List<Policy__c> PolList = New List<Policy>();
PolList = [Select ID, Code__c from Policy__c];

Now from the above query, for suppose, I have 5 records with same values in Code__c (ex: Code__c = 009) field and 3 records having same values (ex: Code__c = 110) and 10 with similar values (ex: Code__c = 876) in that field.

The values in that field might vary and new values might get added for that field.

Is there any way to differentiate the records with similar values from that list.

Please suggest

2
  • 3
    How about using group by Code__c? What are you looking to achieve by identifying Policy__c records of same Code__c value?
    – TSmith
    Jun 12 '20 at 11:59
  • @Tsmith I want to insert these similar value records as child records to a parent object record called Account_Shift__c. Now, suppose, if 3 policy records are having code__c = 876, they should be attached as child records for an Account_Shift__c record
    – SK_112
    Jun 12 '20 at 12:22
0

You need to query using GROUP BY

Query:

List<AggregateResult> PolList = [Select Code__c from Policy__c GROUP BY Code__c];

This will give you 3 records as per your question. Then, you can create Account_Shift__c from them:

List<Account_Shift__c> aShifts = new List<Account_Shift__c>();
for(AggregateResult ar : PolList) {
    aShifts.add(new Account_Shift__c(Code__c=(String)ar.get('Code__c'), ....*other fields*.... ))
}
insert aShifts;
2
  • when i try this, I'm getting the error as "Variable does not exists: Code__c"
    – SK_112
    Jun 17 '20 at 16:20
  • can u try ar.get('Code__c').. Jun 17 '20 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.