Adam Lankford has studied the question:
Psychologists have long theorized that there’s a connection between rage against others and rage against the self. According to my findings, the shooter’s likelihood of committing suicide or suicide by cop appears to be 1.16 times higher (controlling for the attacker’s age and sex) for each additional victim that is killed. This suggests that those who have the most rage toward others – and therefore end up killing the most victims – would also feel the most guilty and ashamed about their crimes. They are therefore more likely to engage in “self-punishment” via suicide or suicide by cop. After the initial explosion of rage causes them to open fire, active shooters who see many dead or dying victims around them may feel a correspondingly higher need for self-punishment than shooters with fewer victims.