perf: speed up report generation

- construct better queries using temp tables outside
  of loop structures