# Query and sub query

**URL:** <https://discuss.elastic.co/t/query-and-sub-query/174403>\
**Category:** Elasticsearch\
**Created:** [March 28, 2019, 5:56pm UTC](https://discuss.elastic.co/t/query-and-sub-query/174403 "2019-03-28T17:56:26Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![lfourny](https://avatars.discourse-cdn.com/v4/letter/l/f19dbf/32.png) [@lfourny](https://discuss.elastic.co/u/lfourny)\
**Post date:** [March 28, 2019, 5:56pm UTC](https://discuss.elastic.co/t/query-and-sub-query/174403/1 "2019-03-28T17:56:26Z")

</div>

Hello everyone,  
I am trying to translate in elasticsearch 'a sql query like the following example:  
`
SELECT numero_serie, Qte_errors
FROM
(
Select
numero_serie as numero_serie,
count(id) as Qte_errors
FROM IndexErrors
WHERE numero_serie IN ( 'GA001', 'GG016', 'GK101', 'GI028','GK040','GL032')
AND error_code IN ('MOT_A1', 'GEN_C8', 'COL_D5','COL_Z8','GEN_B7')
AND (error_date BETWEEN '2019-03-15 00:00:00' AND '2019-03-18 23:59:00')
GROUP BY numero_serie
) AS Results
WHERE Qte_errors >= 2;
`  
Is it possible ?

---

<div class="post-metadata">

**Author:** ![Andrei\_Stefan](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/andrei_stefan/32/47533_2.png) [@Andrei\_Stefan](https://discuss.elastic.co/u/Andrei_Stefan)\
**Post date:** [April 1, 2019, 9:49am UTC](https://discuss.elastic.co/t/query-and-sub-query/174403/2 "2019-04-01T09:49:22Z")

</div>

@lfourny have you tried [Elasticsearch SQL's Translate API](https://www.elastic.co/guide/en/elasticsearch/reference/6.7/sql-translate.html) with the query above? A quick look at the sub-select, I think it should work. I don't recommend running the query exactly as is, because sub-selects are mostly unsupported, but you could try something like the following (and I think it's equivalent to your bigger query):

```auto
SELECT
numero_serie AS numero_serie,
COUNT(id) AS Qte_errors
FROM IndexErrors
WHERE numero_serie IN ('GA001', 'GG016', 'GK101', 'GI028','GK040','GL032')
             AND error_code IN ('MOT_A1', 'GEN_C8', 'COL_D5','COL_Z8','GEN_B7')
             AND (error_date BETWEEN '2019-03-15 00:00:00' AND '2019-03-18 23:59:00')
GROUP BY numero_serie
HAVING Qte_errors >= 2;

```

The translate API will give you a query using some scripts we use internally for the `HAVING` part, but you could come up with your own Painless scripting instead of those, based on what the translate API gives you (should be easy to adapt).

---

<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:** [April 29, 2019, 9:49am UTC](https://discuss.elastic.co/t/query-and-sub-query/174403/3 "2019-04-29T09:49:29Z")

</div>

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