Report Tables query

How would I do that for my data source?

You bring your raw data in as you are now, or possibly unaggregated. Then you add a script data source with a script that will read the above dataset row by row, applying your rules, and inserting a new dataset into the report’s list of keys.
If you need to produce a nested data source, see this forum topic, too.