First stage of SQL aggregation

NB needs optimising. A couple of bugs floating about too.