You can use indeed an entity related to your source data via a reference set. Then write a java program executing the OQL string that uses ID in the SELECT part and populate the reference set.
Mind you, you need 2 versions of the OQL string. One with GROUP BY for aggregates and one without for retrieving the individual records.