2

I have the following SOQL query to display List of ABCs in my Page block table.

Public List<ABC__c> getABC(){
    List<ABC__c> ListABC = [Select WB1__c, WB2__c, WB3__c, Number, tentative__c, Actual__c, PrepTime__c, Forecast__c from ABC__c ORDER BY WB3__c];
    return ListABC;
}

All Rows Displayed

As you can see in the above image, WB3 has number of records for A, B and C. But I want to display only 1 record for each WB3 group based on Actual__c. Only latest Actual__c must be displayed for each WB3 Group.

i.e., Ideally I want to display only 3 rows(one each for A,B,C) in this example.

For this, I have used GROUPBY and displayed the result using AggregateResults. Here is the result.

Max Actual Date and Max Tentative Date

I got the Latest Actual Date for each WB3 as shown above. But the Tentative date is not corresponding to it. The Tentative Date is also the MAX in the list.

Here is the code I used

public List<SiteMonitoringOverview> getSPM(){
        AggregateResult[] AgR = [Select WB_3__c, MAX(Tentaive_Date__c) dtTentativeDate , MAX(Actual_Date__c) LatestCDate FROM Site_progress_Monitoring__c GROUP BY WBS_3__c];

        if(AgR.size()>0){                    

            for(AggregateResult SalesList : AgR){                                                        
                CustSumList.add(new SiteMonitoringOverview(String.ValueOf(SalesList.ge​t('WB_3__c')), String.valueOf(SalesList.get('dtTentativeDate')), String.valueOF(SalesList.get('LatestCDate')) ));            
            }    
        }
        return CustSumList;
    }

I am forced to use MAX() for tentative date. I want the corresponding Tentative date of the MAX Actual Date. Not the Max Tentative Date.

For group A, the Tentative Date of Max Actual Date is 12/09/2012. But it is displaying the MAX tentative date: 27/02/2013. It should display 12/09/2012. This is because I am using MAX(Tentative_Date__c) in my code. Every column in the SOQL query must be either GROUPED or AGGREGATED. That's weird.

How do I get the required 3 rows in this example?

Any suggestions? Any different approach (looping within in groups)? how?

ekad
  • 14,436
  • 26
  • 44
  • 46
sfdcFanBoy
  • 121
  • 1
  • 5

1 Answers1

2

Just ran into this issue myself. The solution I came up with only works if you want the oldest or newest record from each grouping. Unfortunately it probably won't work in your case. I'll still leave this here incase it does happen to help someone searching for a solution to this issue.

AggregateResult[] groupedResults = [Select Max(Id), WBS_3__c FROM Site_progress_Monitoring__c GROUP BY WBS_3__c];

Calling MAX or MIN on the Id will let you get 1 record per group condition. You can then query other information. I my case I just need 1 record from each group and didn't really care which one it was.

NSjonas
  • 10,693
  • 9
  • 66
  • 92