# How to implement SQL 'group by' on multiple fields using aggregations?

**URL:** <https://discuss.elastic.co/t/how-to-implement-sql-group-by-on-multiple-fields-using-aggregations/1361>\
**Category:** Elasticsearch\
**Created:** [May 27, 2015, 7:20am UTC](https://discuss.elastic.co/t/how-to-implement-sql-group-by-on-multiple-fields-using-aggregations/1361 "2015-05-27T07:20:50Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Barak\_Yaish](https://avatars.discourse-cdn.com/v4/letter/b/9de053/32.png) [@Barak\_Yaish](https://discuss.elastic.co/u/Barak_Yaish)\
**Post date:** [May 27, 2015, 7:20am UTC](https://discuss.elastic.co/t/how-to-implement-sql-group-by-on-multiple-fields-using-aggregations/1361/1 "2015-05-27T07:20:50Z")

</div>

Hi all,

I'm trying to implement the following kind of SQL using ES aggs:

select id1, id2, count(\*)  
from mytable  
group by id1, id2;

From what I read this can only accomplished using copy\_to during indexing. Is it indeed the only way or I missed anything?

Thanks!

---

<div class="post-metadata">

**Author:** ![jpountz](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/jpountz/32/45836_2.png) [@jpountz](https://discuss.elastic.co/u/jpountz)\
**Post date:** [May 27, 2015, 11:37am UTC](https://discuss.elastic.co/t/how-to-implement-sql-group-by-on-multiple-fields-using-aggregations/1361/2 "2015-05-27T11:37:36Z")

</div>

I don't think `copy_to` would work as it would still build one bucket per term while you are looking for one bucket per id1, id2 pair if I understand correctly. So you have two options: either an index-time solution and have a dedicated field that stores id1, id2 pairs or a search time solution by using a script that would concatenate those values to build the bucket label. While using scripts would be more flexible, it would also be significantly less efficient.

---

<div class="post-metadata">

**Author:** ![Barak\_Yaish](https://avatars.discourse-cdn.com/v4/letter/b/9de053/32.png) [@Barak\_Yaish](https://discuss.elastic.co/u/Barak_Yaish)\
**Post date:** [May 27, 2015, 8:21pm UTC](https://discuss.elastic.co/t/how-to-implement-sql-group-by-on-multiple-fields-using-aggregations/1361/3 "2015-05-27T20:21:29Z")

</div>

It appears that ES supports sub aggregations, which basically is what I need:

```
{
  "size": 0,
  "aggs": {
    "id1_count": {
      "terms": { "field": "id1" },
      "aggs": {
	"id2_count": {
          "terms": { "field": "id2" }
             }  
           }
        }  
      }
    }
  }
}

```

Thanks!

---

<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 6, 2017, 12:11am UTC](https://discuss.elastic.co/t/how-to-implement-sql-group-by-on-multiple-fields-using-aggregations/1361/4 "2017-07-06T00:11:30Z")

</div>


