you may want to explore using COUNTIF / COUNTIFS for this purpose.

if you can share a sample, it will help us to better visualise the issue.