With this kind of data, SUMIFS/SUMPRODUCT may help. Try them.

If you can not put an end, try to upload a sample worksheet.