With API version 18.0 and later/you can use group by with aggregate functions, such as sum() or max() to summarize the data and enable you to rollup query results rather than having to process the individual records in your code.
Syntax: [ GROUP BY field GROUP BY LIST]