# ESQL pass a stats column to next stage

**URL:** <https://discuss.elastic.co/t/esql-pass-a-stats-column-to-next-stage/373276>\
**Category:** Elasticsearch\
**Tags:** esql\
**Created:** [January 16, 2025, 12:01pm UTC](https://discuss.elastic.co/t/esql-pass-a-stats-column-to-next-stage/373276 "2025-01-16T12:01:00Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mortenb123](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/mortenb123/32/37227_2.png) [@mortenb123](https://discuss.elastic.co/u/mortenb123)\
**Post date:** [January 16, 2025, 12:01pm UTC](https://discuss.elastic.co/t/esql-pass-a-stats-column-to-next-stage/373276/1 "2025-01-16T12:01:00Z")

</div>

I need to find the first and the last inserts of sources in events:

```auto
FROM *.events.* | KEEP @timestamp,source 
| stats latest=max(@timestamp) by source

FROM *.events.* | KEEP @timestamp,source
| stats first=min(@timestamp) by source

```

Now I create two dataframes and merge them based on source

But can a do this in ESQL:

Not working examples:

```auto
# ROW can only take constants:
FROM *.events.* | KEEP @timestamp,source 
| ROW latest=max(@timestamp), first=min(@timestamp)

# stats cut off @timestamp
FROM *.events.* | KEEP @timestamp,source 
| stats latest=max(@timestamp) by source 
| stats first=min(@timestamp) by source

```

---

<div class="post-metadata">

**Author:** ![Wolfram\_Haussig](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/wolfram_haussig/32/70528_2.png) [@Wolfram\_Haussig](https://discuss.elastic.co/u/Wolfram_Haussig)\
**Post date:** [January 16, 2025, 12:49pm UTC](https://discuss.elastic.co/t/esql-pass-a-stats-column-to-next-stage/373276/2 "2025-01-16T12:49:56Z")

</div>

Hello Morten,

You can do multiple aggregations with a single `STATS`:

```auto
FROM *.events.*
| KEEP @timestamp,source 
| STATS earliest=min(@timestamp), latest=max(@timestamp) by source 

```

Is this what you are looking for?

Best regards  
Wolfram

---

<div class="post-metadata">

**Author:** ![mortenb123](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/mortenb123/32/37227_2.png) [@mortenb123](https://discuss.elastic.co/u/mortenb123)\
**Post date:** [January 16, 2025, 1:42pm UTC](https://discuss.elastic.co/t/esql-pass-a-stats-column-to-next-stage/373276/3 "2025-01-16T13:42:50Z")

</div>

> [@Wolfram\_Haussig](#):
>
> `STATS earliest=min(@timestamp), latest=max(@timestamp) by source`

Thanks, somehow I tried that variation, but got errors, but cut and pasted your entry and it works, Thanks

`first` seem to be a protected keyword:

```auto
mismatched input 'first' expecting {QUOTED_STRING, INTEGER_LITERAL, DECIMAL_LITERAL, 'false', '(', 'not', 'null', '?', 'true', '+', '-', NAMED_OR_POSITIONAL_PARAM, OPENING_BRACKET, UNQUOTED_IDENTIFIER, QUOTED_IDENTIFIER}")

```
