[Salesforce] How to use HAVING in SOQL statements

SOQL statement HAVING

HAVING allows you to enter filtering conditions for the results grouped by GROUP BY.

It is similar to WHERE in that it is a filtering condition, but WHERE is before grouping and HAVING is after grouping.

The following sample groups by the lead source of the opportunity and displays the amount by lead source where the number of records with the same value is 1 or more.

AggregateResult[] results = [SELECT LeadSource, SUM(Amount) summary 
                               FROM Opportunity 
                               GROUP BY LeadSource 
                               HAVING Count(LeadSource) > 1];
for(AggregateResult ar: results){
  System.debug('LeadSource='+ ar.get('LeadSource') 
                   + ':Amount='+ ar.get('summary'));
}

Debugging Results

LeadSource=LeadSource1:Amount=2
LeadSource=LeadSource2:Amount=3

投稿者: kinkun

保有資格 Salesforce Certified Platform App Builder T Salesforce Certified Platform Developer I Salesforce Certified Platform Developer II Salesforce Certified Administrator

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です