# Group by field and calculate average value for another field

**URL:** <https://discuss.elastic.co/t/group-by-field-and-calculate-average-value-for-another-field/169176>\
**Category:** Elasticsearch\
**Created:** [February 20, 2019, 10:11am UTC](https://discuss.elastic.co/t/group-by-field-and-calculate-average-value-for-another-field/169176 "2019-02-20T10:11:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![zaartix](https://avatars.discourse-cdn.com/v4/letter/z/f04885/32.png) [@zaartix](https://discuss.elastic.co/u/zaartix)\
**Post date:** [February 20, 2019, 10:11am UTC](https://discuss.elastic.co/t/group-by-field-and-calculate-average-value-for-another-field/169176/1 "2019-02-20T10:11:11Z")

</div>

Mapping:

```
player_id: int
stat_date: date
some_param: int

```

I need to calculate average value for "some\_param" for all player\_id used row with max "stat\_date" in case of several rows with same player\_id.

So i need average value for last date for all players

This snippet it not working because of "Aggregator [average\_val] of type [avg] cannot accept sub-aggregations"

```
get test/test/_search
{
  "size":0,
  "aggs": {
    "average_val":{
      "avg": {
        "field": "some_param"
      },
      "aggs": {
        "by_player": {
          "terms": { "field" : "player_id" },
          "aggs" : {
              "by_date" : { 
                "max" : { "field" : "stat_date" } 
              }
          }
        }
      }
    }
  }
}

```

Simpliest way is use simple avg

```auto
get test/test/_search
{
  "size":0,
  "aggs": {
    "averages": {
      "avg": {
        "field": "some_param"
      }
    }
  }
}

```

But i need to calc avg player "some\_param" only for last stat dates.

---

<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:** [March 20, 2019, 10:11am UTC](https://discuss.elastic.co/t/group-by-field-and-calculate-average-value-for-another-field/169176/2 "2019-03-20T10:11:37Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
