Trouble nesting two bucket aggregations

I am running the following query:

"aggs": {
    "chains": {
      "terms": {
        "field": "E2EID"
      },
      "aggs": {
        "chainresult": {
          "max": {
            "field": "error_code"
          }
        }
      }
    }
  }

And I am getting the following results:

"aggregations": {
    "chains": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "00000000-0000-0000-0000-1462354048000110",
          "doc_count": 13,
          "chainresult": {
            "value": 2
          }
        },
        {
          "key": "00000000-0000-0000-0000-1462354047850268",
          "doc_count": 4,
          "chainresult": {
            "value": 0
          }
        },
        {
          "key": "00000000-0000-0000-0000-1462354045636167",
          "doc_count": 3,
          "chainresult": {
            "value": 0
          }
        },
        {
          "key": "00000000-0000-0000-0000-1462354055161255",
          "doc_count": 2,
          "chainresult": {
            "value": 0
          }
        }
      ]
    }
  }

How can I nest another aggregation here, so I count how many buckets in the aggregation above there are, for each chainresult.value? Basically I would like to derive the following result:

"buckets": [ { "key": "2", "value": "1" }, {"key": "0", "value": "3"} ]

Many thanks,
Dan