=sumifs( Z1:Z100, B1:B100,A1,D1:D100,A2)

change the range to suite your spreadsheet