Hi!
Is it possible to access history data in tags from scripts? This to create calculations such as aggregations (e.g. previous day average production rate) that run on a periodic basis
Thanks
Abel
Hi!
Is it possible to access history data in tags from scripts? This to create calculations such as aggregations (e.g. previous day average production rate) that run on a periodic basis
Thanks
Abel
Hi Abel,
Yes, it is absolutely possible to access historical tag data from scripts.
There are a few ways to achieve this. Here’s one approach that combines a SQL-based Query on your Historian database with a Task script.
Here’s a general outline:
Here’s a simplified example that calculates the average of the last 10 non-null values of a tag called “Tag1”:
public async Task MouseLeftButtonDown1(object sender, System.Windows.Input.InputEventArgs e)
{
var table = await @Dataset.Query.QueryAverageTag1.SelectCommandAsync();
double sum = 0;
int count = 0;
foreach (System.Data.DataRow row in table.Rows)
{
if (double.TryParse(row["Tag1"]?.ToString(), out double value))
{
sum += value;
count++;
}
}
if (count > 0)
{
double average = sum / count;
System.Windows.MessageBox.Show("Average of the last 10 values: " + average.ToString());
}
else
{
System.Windows.MessageBox.Show("No valid values found.");
}
}
This script is triggered by a button click, but you can easily schedule it to run periodically (e.g., every hour or once per day), depending on your aggregation needs.
If your goal is something like “previous day’s average production rate”, you can adjust the SQL query to filter by date range, for example:
SELECT ProductionRate
FROM YourHistorianTable
WHERE Timestamp >= ‘2025-08-03 00:00:00’ AND Timestamp < ‘2025-08-04 00:00:00’
Let me know if this works for you!
Best regards,
Julio Chen
Thanks for providing this information. Very helpful!