I suggest you look at the sumif function.