groupby optimizations

- Fix #307 
- Fix #306 
- Fix #311, Fix #298

The upshot of this change is that @sophieclayton's query that was failing after 12m with OOM errors, failing after 30+ minutes with my manual rewrite, and then working after 2m with my better rewrite -- will now execute the 'correct' plan without any rewriting at all.