Add correct implementations of merge/groupBy to Analysis.

Copious comments to explain the non-trivial logic.