function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sakthidharan Ambayiramsakthidharan Ambayiram 

how to write a single query for counting the records based on different conditions?

For example i want to count the records in opportunity for the conditions like type='New customer' and StageName='Prospecting' in a single query?
plz reply back with your answers, thanks in Advance
Best Answer chosen by sakthidharan Ambayiram
DevADSDevADS
Hi Ambayiram,

This is not feasible to perform using a single query however you can write a SOQL query and create your own aggregators based for the conditions. Refer below example 
 
Integer i=0, j =0;
for(Opportunity oppItr : [SELECT Type, Stagename FROM Opportunity WHERE type='New Customer' OR Stagename = 'Prospecting']){
	if(oppItr.Type == 'New Customer' && oppItr.Stagename == 'Prospecting'){
		i++;
		j++;
	}else if(oppItr.Type == 'New Customer'){
		i++;
	}else if(oppItr.Stagename == 'Prospecting'){
		j++;
	}
	
}
Do post here if you have further questions.

Happy Coding!!
 

All Answers

NagendraNagendra (Salesforce Developers) 
Hi Ambayiram,

Sorry for this issue you are facing.

May I suggest you please refer to below link from the forums community with a similar discussion which might help you further. Please let us know if this helps.

Kindly mark this as solved if the reply was helpful.

Thanks,
Nagendra
sakthidharan Ambayiramsakthidharan Ambayiram
Hi Nagendra,

thanks for your reply, the above mentioned link discussed about multiple conditions for counting the records but i wanted to do a seperate count for multiple conditions 
For Example :
I want to perform the below in a single query
1. To count the opportunity records with type as 'New customer'
2. To count the opportunity records with StageName as 'Prospecting' 
Is it possible to achieve the above two cases in a same query ?
DevADSDevADS
Hi Ambayiram,

This is not feasible to perform using a single query however you can write a SOQL query and create your own aggregators based for the conditions. Refer below example 
 
Integer i=0, j =0;
for(Opportunity oppItr : [SELECT Type, Stagename FROM Opportunity WHERE type='New Customer' OR Stagename = 'Prospecting']){
	if(oppItr.Type == 'New Customer' && oppItr.Stagename == 'Prospecting'){
		i++;
		j++;
	}else if(oppItr.Type == 'New Customer'){
		i++;
	}else if(oppItr.Stagename == 'Prospecting'){
		j++;
	}
	
}
Do post here if you have further questions.

Happy Coding!!
 
This was selected as the best answer