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