There are several ways of doing this.
One would be to sort your GroupBy results using a for loop.
Another would be to put the results into map(s). Then take the top two results from your sorting in order to get them for the respective parents.
Since you're using a GroupBy, you could also presumably return something "like" ar[0].cnt, ar[0].Parent__r.Primary_Category__c
and ar[1].cnt, ar[1].Parent__r.Primary_Category__c
to get the top two for the parent with the "most" results and compare the two Parent_r's
to see if they're the same. If they're not, you have the two that you're looking for that are at the top.
If they are the same, you'll need to test ar[3]
, ar[4]
, etc until you find a different Parent__r
to assign as the second parent.
From the above, you'll already know the results for the highest Primary_Category__c
for the first Parent__r
and for the 2nd one as well. Now you need to sort the secondary category based on the what you learned determined to be the 1st and second parents.
I believe this is where you may want to put the results into two maps.
Beginning with the 1st parent, do a for loop to add the results of a loop to the map if the parent and the secondary_category__c
matches parent__r
that was the 1st parent
and secondary_category__c isEmpty() == false
. The first result you find will be the one you're looking for. Rather than putting it into a map, you could break
from the for loop
if you wanted to. the choice would be yours to make.
You'd repeat the same process above for the other parent__r
.
Best Answer
If your criteria date is fixed here is what i would do:
Create new field say "Group_type" update this field based on criteria using Trigger/ workflow
use this Group_type field in query for grouping
List<AggregatedResult> results = [Select count(Id) From Job__c Group By Group_type ];
This should give you same result with with one query
Note that it will return both groups in different rows but you can write apex logic around it to get the data.