Order the results by the relevant value so you can work with all the results for a given id at the same time, then move to a new id.
if you can't do that, then you have to keep all objects in memory, which, depending on the number of records, may cause memory problems.
Use an ORDER BY [unique id] clause in your query so the result set keeps all the records with that ID together. Simply loop through the result set, merging records until the ID changes. Then start a new record. Easy as pie.