The database server, in this case, MySQL, is perfectly capable of calculating averages and whatnot as you're pulling data out of the database. Check out the
MySQL Manual Numeric Functions.
And as always, the absolute most important thing to do is always
use strict; and
use warnings;