refactoring some sums into sql queries