SQL nested queries

Previously we avoided nested queries and tried to collapse as much as possible into a single query.  This causes some wrong results because some operations, like groupbys and joins don't commute.

We're now more strict about nesting queries and aliasing them.