# How to create dynamic scripted field based on date-time range selection

**URL:** <https://discuss.elastic.co/t/how-to-create-dynamic-scripted-field-based-on-date-time-range-selection/373045>\
**Category:** Kibana\
**Created:** [January 10, 2025, 7:28am UTC](https://discuss.elastic.co/t/how-to-create-dynamic-scripted-field-based-on-date-time-range-selection/373045 "2025-01-10T07:28:32Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![rkidev](https://avatars.discourse-cdn.com/v4/letter/r/e95f7d/32.png) [@rkidev](https://discuss.elastic.co/u/rkidev)\
**Post date:** [January 10, 2025, 7:28am UTC](https://discuss.elastic.co/t/how-to-create-dynamic-scripted-field-based-on-date-time-range-selection/373045/1 "2025-01-10T07:28:32Z")

</div>

I want to create dynamic scripted field **(Avg(NA-NB))**, which is the average of **NA-NB** field values based on the date-time range selection.

 ![image](https://us1.discourse-cdn.com/elastic/original/3X/3/3/33c6ee91afbc0ec838053323e84336d42319675f.png)

Currently the average is calculated on the total rows of the NA-NB. What I want is that, if I select the date-time from "2025-01-09 07:30:00" to "2025-01-09 07:30:08", so the average should be calculated on the total of first 9 rows, not all the rows. OR  
can we calculate average in Kibana lens or TSVB?

---

<div class="post-metadata">

**Author:** ![Marco\_Liberati](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/marco_liberati/32/82953_2.png) [@Marco\_Liberati](https://discuss.elastic.co/u/Marco_Liberati)\
**Post date:** [January 10, 2025, 2:29pm UTC](https://discuss.elastic.co/t/how-to-create-dynamic-scripted-field-based-on-date-time-range-selection/373045/2 "2025-01-10T14:29:35Z")

</div>

I assume for each @timestamp bucket there's probably an `average` to compute (here is every 3 hours). Next to it the `overall_average(...)` formula is used to compute across the entire table data: this will dynamically change based on the date -time range.

 ![Screenshot 2025-01-10 at 15.28.10](https://us1.discourse-cdn.com/elastic/original/3X/6/1/61cffbbc9a52f87153af0bcd1fe0fa05ebe1bf1d.png)
