# How can I have both sum and groupby in a single aggregation Elasticsearch?

**URL:** <https://discuss.elastic.co/t/how-can-i-have-both-sum-and-groupby-in-a-single-aggregation-elasticsearch/63095>\
**Category:** Elasticsearch\
**Created:** [October 15, 2016, 8:52am UTC](https://discuss.elastic.co/t/how-can-i-have-both-sum-and-groupby-in-a-single-aggregation-elasticsearch/63095 "2016-10-15T08:52:52Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Kulasangar\_Gowrisang](https://avatars.discourse-cdn.com/v4/letter/k/ce73a5/32.png) [@Kulasangar\_Gowrisang](https://discuss.elastic.co/u/Kulasangar_Gowrisang)\
**Post date:** [October 15, 2016, 8:52am UTC](https://discuss.elastic.co/t/how-can-i-have-both-sum-and-groupby-in-a-single-aggregation-elasticsearch/63095/1 "2016-10-15T08:52:52Z")

</div>

I'm able to send `HTTP POST` requests individually for `sum` & `groupby` using `aggs` in order to filter data from the index which I created through `logstash`.

This is how I tried querying for `groupby`:

```
    "aggs":{  
      "total":{  
         "terms":{  
            "field":"responsecode"
         },
         "aggs":{  
            "grades_count":{  
               "value_count":{  
                  "script":"Integer.parseInt(doc['responsecode'].value)"
               }
            }
         }
      }
   }

```

And this is how I tried querying for `sum`:

```
"aggs":{  
      "total":{  
         "terms":{  
            "field":"userid"
         },
         "aggs":{  
            "grades_count":{  
               "value_count":{  
                  "script":"doc['userid'].value"
               }
            }
         }
      }
   }

```

So what I need now is to have both of them in a single `aggs` so that I can get both the sum and the group by results.

This is the `MySQL` query which i'm trying to apply it in `elasticsearch`:

```
select userId, sum(chargeAmount+0) from sb_api_response_summary where group by userId;

```

Where am i going wrong? Any help could be appreciated.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 5, 2017, 10:12pm UTC](https://discuss.elastic.co/t/how-can-i-have-both-sum-and-groupby-in-a-single-aggregation-elasticsearch/63095/2 "2017-07-05T22:12:04Z")

</div>


