Refactor nested merge in database

Refactor the code that merged grouped periodic query results into the
nested data structure that is returned by backdrop.

This code simplifies the code `nested_merge` function and moves it out
into it's own module (`backdrop.core.nested_merge`).

This also adds collected fields to subgroups as well as just the root.

All parts of the function are now recursive so multiple levels of
grouping can be handled.

WIP: Some tests have not been written yet.