Schema
I have a scenario where two records are related via Lookup.
A -> B(has Lookup[A])
So parent A can have many related children B objects.
Since A and B are related through lookup and not through Master-Detail, Owner of A will be different from Owner of related children B objects
Problem:
I want to find the maximum count of owners for B with given parent A and assign it to parent A object. Please provide me an approach using SOQL(recommended) or Apex.
My Try
Took SOQL result of B's Owner with A.Id
[Select A.Id,B.OwnerId From B]
Formed a Map with key as A.Id and value as OwnerIds
Map<Id,List<Id>> AToOwner = new Map<Id,List<Id>>()
Convert the List to occurrence hash
{U1,U1,U2} => { U1 => 2, U2 => 1}
Find the Max occurence Owner and set the Owner for parent A
A.OwnerId = U1 // Since U1 has max occurence of 2
Currently it works fine for smaller record set of size 100 but fails with CPU limit exceeded for larger size.
Test Input Data
A | B | B's Owner
----------------
1 X U1
1 Y U1
1 Z U2
2 A U3
Expected Output result
A | OwnerId | Count as B's Owner
------------------------------
1 U1 2
2 U3 1