# How to calc percentage $$$%%%?

**URL:** https://discuss.elastic.co/t/how-to-calc-percentage/64247
**Category:** Elasticsearch
**Created:** [October 28, 2016, 6:43am UTC](https://discuss.elastic.co/t/how-to-calc-percentage/64247 "2016-10-28T06:43:08Z")
**Posts on this page:** 4
**Page:** 1

<div class="post-metadata">

### Author: ![NativAt](https://avatars.discourse-cdn.com/v4/letter/n/fbc32d/32.png) [@NativAt](https://discuss.elastic.co/u/NativAt)
#### Post date: [October 28, 2016, 6:43am UTC](https://discuss.elastic.co/t/how-to-calc-percentage/64247/1 "2016-10-28T06:43:08Z")

</div>

I need to calc percentage of 2 aggs fields.

example:  
sum(maple\_tree) / sum(all\_types\_of\_trees);

result:  
maple tree percent % from all all types of trees.

P.S.  
I prefer to do the calc on the query itself and not in the code.

---

<div class="post-metadata">

### Author: ![shanec](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/shanec/32/4004_2.png) [@shanec](https://discuss.elastic.co/u/shanec)
#### Post date: [October 28, 2016, 1:32pm UTC](https://discuss.elastic.co/t/how-to-calc-percentage/64247/2 "2016-10-28T13:32:42Z")

</div>

Have you looked at pipeline aggregations? Specifically, the [bucket script aggregation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-pipeline-bucket-script-aggregation.html) has an example that calculates a percentage

---

<div class="post-metadata">

### Author: ![NativAt](https://avatars.discourse-cdn.com/v4/letter/n/fbc32d/32.png) [@NativAt](https://discuss.elastic.co/u/NativAt)
#### Post date: [November 12, 2016, 3:00pm UTC](https://discuss.elastic.co/t/how-to-calc-percentage/64247/3 "2016-11-12T15:00:39Z")

</div>

Yes, but I need to calc percentage from the "Total" of 2 fields, and not per bucket computations.

For example: get the the "total" sales percentage of red cars.

```
GET /sales/_search
{
	"size": 0,
	"aggs": {
		"sales_per_month": {
			"date_histogram": {
				"field": "date",
				"interval": "month"
			},
			"aggs": {
				"red_cars": {
					"sum": {
						"field": "red"
					},
					"sold_red_card": {
						"value_count": {
							"field": "sold"
						}
					}
				}
			}
		}
	}
}
```

---

<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:05pm UTC](https://discuss.elastic.co/t/how-to-calc-percentage/64247/4 "2017-07-05T22:05:53Z")

</div>


