This is really an SQL question. Are you using MySQL? If so, they have some helpful pages online, e.g. HERE for how to construct your queries (though I must say there's a bit of a learning curve to figure out their "help"). Whichever database you're using should be able to do the calculation you need right from the query.