Historian Retrieval

Download as pdf or txt
Download as pdf or txt
You are on page 1of 213

Wonderware

Historian

Retrieval Guide
Version 17.0.18000

March 2017
© 2017 Schneider Electric Software, LLC. All rights reserved.
No part of this documentation shall be reproduced, stored in a ret rieval system, or transmitted by any
means, electronic, mechanical, photocopying, rec ording, or otherwise, without the prior written
permission of Schneider Electric Soft ware, LLC. No liability is assumed with respect to the use of the
information contained herein.
Although precaution has been taken in the preparation of this documentation, Schneider Electric
Software, LLC assumes no responsibility for errors or omissions. The information in this documentation
is subject to change without notice and does not represent a commitment on the part of Schneider
Electric Software, LLC. The software described in this documentation is furnished under a license
agreement. This software may be used or copied only in accordance wit h the terms of such license
agreement.
ArchestrA, A vantis, DYNS IM, eDNA, EYESIM, Foxboro, Foxboro E vo, I/A S eries, InBatch, InduS oft,
InStep, IntelaTrac, InTouch, PIPEPHASE, PRiSM, PRO/ II, PROVIS ION, ROMeo, Schneider Electric,
SIM4ME, SimCentral, SimSci, Skelta, SmartGlance, Spiral Soft ware, VIS UAL FLA RE, WindowMaker,
WindowViewer, and Wonderware are trademarks of Schneider Electric SE, its subsidiaries, and
affiliated companies. An extensive listing of Schneider Electric Soft ware, LLC trademarks can be found
at: http://software.schneider-electric.com/legal/trademarks/. All other brands may be trademarks of
their respective owners.
Schneider Electric Soft ware, LLC
26561 Rancho Park way South
Lake Forest, CA 92630 U.S.A.
(949) 727-3200
http://software.schneider-electric.com/
Publication date: 4/3/2017
Contact Us
Contact Schneider Electric Software Technical Support
Avanti s Technical Support
Listing of regional and local country contacts: http://software.schneider -electric.com/support/avantis/
Technical support: http://softwares upport.schneider-electric.com/
For A vantis.PRO, A vantis Approvals, Avantis.DSS, and Condition Manager:
 Email: [email protected]
 Phone (8:30 a.m. to 5:00 p.m. Monday to Friday, Eastern Time):
o Toll-Free U.S. and Canada: 1-888-262-7111
o Toll-Free EMEA: 1-800-4670-6466
o Direct dial: 1-905-632-0635
For A vantis. XA:
 Email: [email protected]
 Phone (8:30 a.m. to 5:00 p.m. Monday to Friday, Eastern Time):
o Toll-Free U.S. and Canada: 1-800-991-8000
o Toll-Free EMEA: 1-800-4670-6466
o Direct dial: 1-905-632-4122
SimSci Technical Support
Listing of regional and local country contacts: http://software.schneider -electric.com/support/simsci/
Technical support: http://softwares upport.schneider-electric.com/
 Email U.S. and Canada: [email protected]
 Phone (USA 8:00 a.m. to 5:00 p.m. Central Time)
o Toll-Free U.S. and Canada: 1-800-746-7241
Skelta Technical Support
 Email: [email protected]
 Phone:
o U.S.: 1-678-306-4110 Option 3
o India: 91-80-4060-2600 Option 3
Wonderware Technical Support
Listing of regional and local country contacts: https://www.wonderware.com/contact/contact -support/
Technical support: http://softwaresupport.schneider-electric.com/
 Priority email for Customer FIRS T Members: custfirstsupport @wonderware.com
 Email for customers without a support agreement: [email protected]
 Phone
o Toll-Free North America and Latin Americ a: 1-800-966-3371
o Direct dial: 1-949-639-8500
InStep Technical Support
Cont act page: http://www.instepsoftware.com/contact-us
Technical support: https://support.instepsoft ware.com/
 Email: [email protected]
 Phone (USA 8:00 a.m. to 5:00 p.m. Central Time)
o 1-312-894-7870
Schneider Electric – Smart Water Software Technical Support
 Help desk email: [email protected]
 Help desk telephone hotline: +45 88 30 20 77 (09:00 to 16:00 Monday to Thurs day, Friday 09:00 to
15:00, Central European Time)
Contact Schneider Electric Software Learning Services
Cont act Software Learning Services for assistance regarding classes, schedule, offerings, frequently
asked questions, tuition, policies, and more.
 Email: [email protected]
 Toll-Free U.S. and Canada: 1-866-998-7246
 Direct: 1-949-639-8508
 Fax: 1-949-639-1847
Wonderware Historian Retrieval Guide

Contents
Welcome .................................................................................................................................. 11
Wonderware Historian Documentation Set ................................................................................ 11

Chapter 1 About Data Retrieval......................................................................................... 13


Data Retrieval Subsystem Features ......................................................................................... 13
History Blocks: A SQL Server Remot e Dat a Source .................................................................. 14
Retrieval subsystem ................................................................................................................ 14
About the Wonderware Historian OLE DB Provider ................................................................... 14
Extension Tables for History Data ...................................................................................... 15
Linking the Wonderware Historian OLE DB Provider to the Microsoft SQL Server ................. 16
Wonderware Historian I/O Server ............................................................................................. 17
Using SELE CT to Retrieve Data .............................................................................................. 17
Using the Four-Part Naming Convention ............................................................................. 18
Using a Wonderware Historian OLE DB Provider View ........................................................ 19
Using the OPE NQUERY Function ...................................................................................... 19
Using the OPE NROWSET Function ................................................................................... 20
Supported Syntax Options ................................................................................................. 20
Unsupported or Limited Syntax Options .............................................................................. 21
No Notion of Client Context .......................................................................................... 21
Limitations on Wide Tables .......................................................................................... 21
LIKE Clause Limitations ............................................................................................... 21
IN Claus e Limitations ................................................................................................... 21
OR Clause Limit ations ................................................................................................. 22
Using Joins within an OPE NQUERY Function ............................................................... 22
Using Complicat ed Joins .............................................................................................. 23
Using a Sub-SELE CT with a SQL Server Table and an Extension Table ......................... 23
WHERE Clause Anomalies .......................................................................................... 23
CONVERT Function Limitations ................................................................................... 24
SQL Server Optimization of Complex Queries ............................................................... 24
Using Columns of a Variant Type with Functions ........................................................... 25
Using Start DateTime in the Query Criteria ..................................................................... 26
Comparison Statements and NULL Values.................................................................... 26
OPENQUERY and Microsoft Query .............................................................................. 26
Wonderware Historian Time Domain Extensions ................................................................. 26

Chapter 2 Data Retrieval Options ..................................................................................... 29


Understanding Retrieval Modes ............................................................................................... 29
Cyclic Retrieval ................................................................................................................. 29
Cyclic Retrieval - How It Works..................................................................................... 30
Cyclic Retrieval - Supported Value Parameters ............................................................. 30
Cyclic Retrieval - Query Example ................................................................................. 31
Cyclic Retrieval - Initial Values...................................................................................... 32
Cyclic Retrieval - Handling NULL Values ....................................................................... 32

Version 17.0.18000 5
Wonderware Historian Retrieval Guide Contents

Delta Retrieval .................................................................................................................. 32


Delta Retrieval - How It Works ...................................................................................... 32
Delta Retrieval - Supported Value Parameters............................................................... 33
Delta Retrieval - Query Examples ................................................................................. 33
Delta Retrieval - Initial Values ....................................................................................... 36
Delta Retrieval - Handling NULL Values ........................................................................ 36
Full Retrieval ..................................................................................................................... 37
Full Retrieval - How It Works ........................................................................................ 38
Full Retrieval - Supported Value Paramet ers ................................................................. 38
Full Retrieval - Query Example ..................................................................................... 38
Full Retrieval - Initial Values ......................................................................................... 39
Interpolated Retrieval ........................................................................................................ 39
Interpolated Retrieval - How It Works ............................................................................ 39
Interpolated Retrieval - Query Examples ....................................................................... 40
Interpolated Retrieval - Initial and Final Values .............................................................. 43
Interpolated Retrieval - Handling NULL Values .............................................................. 43
Best Fit Retrieval ............................................................................................................... 43
Best Fit Retrieval - How It Works .................................................................................. 45
Best Fit Retrieval - Support ed Value Parameters ........................................................... 46
Best Fit Retrieval - Query Example ............................................................................... 46
Best Fit Retrieval - Initial and Final Values .................................................................... 47
Best Fit Retrieval - Handling NULL Values .................................................................... 48
A verage Ret rieval .............................................................................................................. 48
A verage Ret rieval - How It Works ................................................................................. 49
A verage Ret rieval - Supported Value Parameters .......................................................... 50
A verage Ret rieval - Query Examples ............................................................................ 50
A verage Ret rieval - Initial and Final Values ................................................................... 52
A verage Ret rieval - Handling NULL Values ................................................................... 52
Minimum Retrieval ............................................................................................................. 52
Minimum Retrieval - How It Works ................................................................................ 53
Minimum Retrieval - Supported Value Parameters ......................................................... 53
Minimum Retrieval - Query Examples ........................................................................... 54
Minimum Retrieval - Initial and Final Values .................................................................. 55
Minimum Retrieval - Handling NULL Values and Incomplete Cycles ............................... 56
Maximum Retrieval ............................................................................................................ 57
Maximum Retrieval - How It Works ............................................................................... 57
Maximum Retrieval - Supported Value Parameters ........................................................ 58
Maximum Retrieval - Query Examples .......................................................................... 58
Maximum Retrieval - Initial and Final Values ................................................................. 60
Maximum Retrieval - Handling NULL Values and Incomplete Cycles .............................. 60
Integral Retrieval ............................................................................................................... 62
Integral Retrieval - How It Works .................................................................................. 62
Integral Retrieval - Supported Value Paramet ers ........................................................... 62
Integral Retrieval - Query Example ............................................................................... 63
Integral Retrieval - Initial and Final Values ..................................................................... 63
Integral Retrieval - Handling NULL Values .................................................................... 63
Slope Retrieval .................................................................................................................. 64
Slope Retrieval - How It Works ..................................................................................... 64
Slope Retrieval - Supported Value Parameters .............................................................. 65
Slope Retrieval - Query Example .................................................................................. 65
Slope Retrieval - Initial and Final Values ....................................................................... 66
Slope Retrieval - Handling NULL Values ....................................................................... 66
Counter Retrieval .............................................................................................................. 66
Counter Retrieval - How It Works.................................................................................. 67
Counter Retrieval - Calculations for a Manually Reset Counter ....................................... 68

6 Version 17.0.18000
Contents Wonderware Historian Retrieval Guide

Counter Retrieval - Using a Count er Deadband ............................................................. 68


Counter Retrieval - Supported Value Paramet ers .......................................................... 69
Counter Retrieval - Initial and Final Values .................................................................... 69
Counter Retrieval - Handling NULL Values .................................................................... 69
Counter Retrieval - Handling Illegal Values.................................................................... 69
Counter Retrieval - Query Example .............................................................................. 69
ValueState Retrieval .......................................................................................................... 70
ValueState Retrieval - How It Works ............................................................................. 71
ValueState Retrieval - Support ed Value Parameters ...................................................... 72
ValueState Retrieval - Query Examples ........................................................................ 72
ValueState Retrieval - Initial and Final Values ............................................................... 75
ValueState Retrieval - Handling NULL Values ............................................................... 75
RoundTrip Retrieval .......................................................................................................... 76
RoundTrip Retrieval - How It Works .............................................................................. 76
RoundTrip Retrieval - Support ed Value Parameters ....................................................... 77
RoundTrip Retrieval - Query Examples ......................................................................... 77
RoundTrip Retrieval - Initial and Final Values ................................................................ 78
RoundTrip Retrieval - Handling NULL Values ................................................................ 78
Edge Detection for E vents (wwE dgeDetection) .............................................................. 78
Predictive Filter ................................................................................................................. 87
Understanding Retrieval Options .............................................................................................. 88
Which Options Apply to Which Retrieval Modes? ................................................................ 88
Using Retrieval Options in a Trans act-SQL Statement ......................................................... 89
Cycle Count (X V alues over Equal Time Intervals ) (wwCycleCount)...................................... 90
Cycle Count - Query Examples ..................................................................................... 91
Resolution (Values Spaced E very X ms) (wwResolution) ..................................................... 92
Resolution - Query Example......................................................................................... 93
About Phantom Cycles ...................................................................................................... 94
Time Deadband (wwTimeDeadband).................................................................................. 96
Time Deadband - Query Examples ............................................................................... 97
Value Deadband (wwValueDeadband) ............................................................................. 100
Value Deadband - Query Examples ............................................................................ 100
History Version (wwVersion) ............................................................................................ 103
History Version - Query Example ................................................................................ 103
Interpolation Type (wwInterpolationType) .......................................................................... 104
Timestamp Rule (wwTimestampRule) ............................................................................... 106
Time Zone (wwTimeZone) ............................................................................................... 110
Quality Rule (wwQualityRule) ........................................................................................... 111
Quality Rule - Query Examples ................................................................................... 112
State Calculation (wwStateCalc ) ...................................................................................... 118
Analog Value Filtering (wwFilter) ...................................................................................... 119
Statistically Removing Outliers (SigmaLimit) ................................................................ 120
Converting Analog Values to Discrete Values (ToDiscrete) ........................................... 121
"Zeroing" Around a Base Value (Sna pTo) ................................................................... 123
Selecting Values for Analog Summary Tags (wwV alueSelector) ......................................... 124

Chapter 3 SQL Query Examples ..................................................................................... 129


Querying the History Table .................................................................................................... 131
Querying the Live Table ........................................................................................................ 131
Querying the WideHistory Table............................................................................................. 132
Querying Wide Tables in Delta Retrieval Mode ....................................................................... 133

Version 17.0.18000 7
Wonderware Historian Retrieval Guide Contents

Querying the AnalogSummaryHistory View............................................................................. 134


Querying the StateS ummaryHistory View ............................................................................... 134
Using an Unconventional Tagname in a Wide Table Query ...................................................... 135
Using an INNE R REMOTE JOIN............................................................................................ 136
Setting Both a Time and Value Deadband for Retrieval ........................................................... 136
Using wwResolution, wwCycleCount, and wwRet rievalMode in the Same Query ....................... 139
Determining Cycle Boundaries ............................................................................................... 139
Mixing Tag Types in the Same Query ..................................................................................... 140
Using a Criteria Condition on a Column of Variant Data ........................................................... 141
Using DateTime Functions..................................................................................................... 141
Using the GROUP BY Clause ................................................................................................ 143
Using the COUNT() Function ................................................................................................. 143
Using an Arithmetic Function ................................................................................................. 144
Using an Aggregate Function................................................................................................. 144
Making and Querying Annotations .......................................................................................... 146
Using Comparison Operators with Delta Retrieval ................................................................... 146
Specifying the Start Dat e with ">=" ................................................................................... 147
Specifying the Start Dat e with ">" ..................................................................................... 148
Specifying the End Date wit h "<=" .................................................................................... 150
Specifying the End Date wit h "<" ...................................................................................... 150
Using Comparison Operators with Cyclic Retrieval and Cycle Count ........................................ 151
Specifying Cycle Count with Two Equity Operators ............................................................ 151
Specifying Cycle Count with One Equity Operator ............................................................. 152
Specifying Cycle Count with No Equity Operators .............................................................. 153
Using Comparison Operators with Cyclic Retrieval and Resolution ........................................... 154
Using Two Equality Operators for Comparison wit h Cyclic Retrieval and Resolution ............ 154
Using One Equality Operator for Comparison with Cyclic Retrieval and Resolution .............. 155
Using No Equality Operators for Comparison with Cyclic Retrieval and Resolution ............ 156
Returning Time Bet ween Value Changes ............................................................................... 157
Example 1: Cyclic Retrieval .............................................................................................. 157
Example 2: Delt a and Full Retrieval .................................................................................. 158
Example 3: Querying the WideHistory Table ..................................................................... 159
Example 4: Querying the History Ta ble wit h the wwValueSelector Parameter ..................... 160
Example 5: Calc ulating Total Time Bet ween Value Changes .............................................. 161
SELECT INTO from a History Table ....................................................................................... 162
Moving Data from a SQL Server Table to an Extension Table .................................................. 163
Using Server-Side Curs ors .................................................................................................... 164
Using Stored Procedures in OLE DB Queries ......................................................................... 165
Getting Data from the OPCQualityMap Table .......................................................................... 165
Using Variabl es with the Wide Table ...................................................................................... 166
Retrieval Across a Data Gap in Classically Stored Data ........................................................... 166
Returned Values for Non-V alid Start Times ............................................................................. 168

8 Version 17.0.18000
Contents Wonderware Historian Retrieval Guide

Querying Aggregate Data in Different Ways............................................................................ 168


Bitwise Retrieval for Process Data ......................................................................................... 170

Chapter 4 SQL Queries for Alarms and Events ............................................................ 173


Querying Alarms and E vents ................................................................................................. 173
Datetime in Alarm and E vent Queries ..................................................................................... 174
Example: Listing all events............................................................................................... 174
Example: How often alarms occur .................................................................................... 174
Example: Most frequent alarm per hour ............................................................................ 175
Example: Pinpointing where alarms occur ......................................................................... 176
Example: Showing average time to clearing an alarm ........................................................ 177
Example: E valuating response time for alarms .................................................................. 178

Chapter 5 Browser-Friendly Data Retrieval ................................................................... 181


About Data Retrieval Using the iHistory Interface .................................................................... 181
About the OData Web Protocol ........................................................................................ 181
iHistory and Account Authentication ................................................................................. 182
Querying the Historian Dat abas e ........................................................................................... 182
Using Date Time Filters ................................................................................................... 182
Process History Query Options ........................................................................................ 183
E vent Data Query Options ............................................................................................... 184
ODat a Query Examples ................................................................................................... 184
Summary History Query Options ...................................................................................... 185
Using the Excel OData Feed to Import Process or E vent Dat a ................................................. 186
Querying History Blocks via SQL S erver Reporting Services Extension .................................... 188
Supported OData Retrieval Syntax ......................................................................................... 189
Resources for OData Queries .......................................................................................... 190
Supported Syntax Tokens and Operators.......................................................................... 191
Resources ............................................................................................................................ 193
Tags ............................................................................................................................... 194
TagProperties ................................................................................................................. 195
TagPropertyValues.......................................................................................................... 195
TagGroups ..................................................................................................................... 195
TagSuggest .................................................................................................................... 196
TagSearch ...................................................................................................................... 196
TagExtendedP roperties ................................................................................................... 197
ProcessValues ................................................................................................................ 198
SystemParameters .......................................................................................................... 198
Summary Resources ............................................................................................................. 199
Summary Structure ......................................................................................................... 199
Daily ............................................................................................................................... 199
Hourly ............................................................................................................................ 205
Minutely .......................................................................................................................... 206
E vent Resources .................................................................................................................. 206
E vent Data Structure ....................................................................................................... 207
Provider Dat a Structure ................................................................................................... 207
User Data Structure......................................................................................................... 208
Source Data Structure ..................................................................................................... 208
Alarm Data Structure ....................................................................................................... 209
Verifier Data Structure ..................................................................................................... 210

Version 17.0.18000 9
Wonderware Historian Retrieval Guide Contents

Flexible Properties........................................................................................................... 210


Errors ................................................................................................................................... 211

10 Version 17.0.18000
Wonderware Historian Retrieval Guide

Welcome
This guide describes how to retrieve data that is stored by a Wonderware Historian server.
You can retrieve data by using:
 Trans act-SQL queries.
 Historian Client tools for query construction, queries within Excel workbooks, and trend mapping.
 Historian InSight, a web-based tool for tag-based searches and charting. With InSight, you can
save and reuse cont ent (sets of tags and defined timeframes ), and can share, embed, and
download the results. Historian InSight is installed as a part of Wonderware Historian.
 Historian SDK.
 Tools that use the RES T ODat a interface.

Wonderware Historian Documentation Set


The Wonderware Historian documentation set includes the following guides:
 Wonderware System Platform Installation Guide
This guide provides information on installing the Wonderware Historian, including hardware and
software requirements and migration instructions.
 Wonderware Historian Concepts Guide
This guide provides an overview of the entire Wonderware Historian system and its key
components.
 Wonderware Historian Scenarios Guide
This guide discusses how to use Won derware Historian to address some common customer
scenarios.
 Wonderware Historian Administration Guide
This guide describes how to administer and maintain an installed Wonderware Historian, such as
configuring data acquisition and storage, managing securit y, and monitoring the system.
 Wonderware Historian Retrieval Guide
This guide describes the retrieval modes and options that you can use to retrieve your data.
 Wonderware Historian Database Reference
This guide provides documentation for all of the Wonderware Historian databas e entities, such as
tables, views, and stored procedures.
 Wonderware Historian Glossary
This guide provides definitions for terms used throughout the documentation set.
In addition, the Schneider Electric License Manager Guide describes the Schneider Electric License
Manager and how to use it to install, maintain, and delete licenses and licens e servers on local and
remot e computers.

Version 17.0.18000 11
Wonderware Historian Retrieval Guide

C HAPTER 1
About Data Retrieval
Through the Data Retrieval subsystem, Wonderware Historian receives SQL queries from clients,
locates the requested data, performs necessary processing, and then returns the results.
For configuration and event data, retrieval is made possible by normal SQL queries, because these
types of data are stored in SQL Server database tables. Historical data, however, must be retrieved
from history blocks and then sent to clients as if it is stored in SQL Server tables.
To accomplish retrieval from both data repositories, the Data Retrieval subsystem includes:
 An implementation of a SQL Server data provider.
This determines whether the requested data is saved in SQL Server tables or in history blocks.
 Retrieval subsystem.
This subsystem is responsible for extracting the requested data from the history blocks and
presenting to the Wonderware Historian OLE DB provider as "virtual" history tables.
 A set of SQL Server extensions.
These are implemented as columns in the history tables. You can us e these extensions to specify
the nature of the rowset that is returned, such as the number of rows returned, the resolution of the
data, or the retrieval mode.
For more information on data storage, see Managing Data Storage.

In This Chapter
Data Retrieval Subsystem Features ............................................................................................... 13
History Blocks: A SQL Server Remot e Dat a Source ........................................................................ 14
Retrieval subsystem...................................................................................................................... 14
About the Wonderware Historian OLE DB Provider ......................................................................... 14
Wonderware Historian I/O Server................................................................................................... 17
Using SELE CT to Retrieve Data .................................................................................................... 17

Data Retrieval Subsystem Features


Data Retrieval subsystem features include support for:
 Queries with all tag types
You can include all tag types in the same query when retrieving from the History table. Any
combination of tags can be submitted in a single query.
 Both fixed- and variable-length strings
 FILETIME for time computations
All internal time computation and manipulation is done using the Win32 FILE TIME type. The
resolution of FILE TIME is 100 nanoseconds.

Version 17.0.18000 13
Wonderware Historian Retrieval Guide About Data Retrieval

 Time handled as Universal Time Coordinated


All times are handled internally as UTC. Conversions to and from local time are handled going in
and out of retrieval so the external interfac e is local time.
 Retrieval of different versions

Note: If you have an application that uses the older SQL Server dat etime format, be aware that some
rounding can occur as compared to the newer datetime2 format (for example, 3.3ms vs. 100ns).

History Blocks: A SQL Server Remote Data Source


History block s are remote data sources used by Wonderware Historian. That is, they are data
repositories that exist outside of a SQL Server database file (.MDF). Microsoft sometimes refers to
these types of data sources as "non-loc al data stores."
All tag data is stored in history blocks. For more information on history blocks, see Managing Partitions
and History Blocks in the Wonderware Historian Administration Guide.
OLE DB technology can be used to access data in any remote data store. This access is accomplished
though a soft ware component called an OLE DB provider.

Retrieval subsystem
The Retrieval subsystem does the following:
 Fetches history data from history blocks on disk.
 Formats data so that it can be passed up through the system to the Wonderware Historian OLE DB
provider or other HCAL-enabled client applications.
 Returns information regarding the history blocks, such as the start and end dates and the location.

About the Wonderware Historian OLE DB Provider


OLE DB (short for "Object Linking and Embedding for Databases") is an application programming
interface (AP I) that allows COM-based client applications to access data that is not physically stored in
the SQL Server to which they are connecting.
OLE DB provides access to different types of data in a broader manner. By using OLE DB, you can
simultaneously access data from a variety of sources. A query that accesses data from multiple,
dissimilar data sources such as these is called a "heterogeneous" or "distributed" query.
SQL Server uses OLE DB to make linking dat a between the dat a sources easier. Through OLE DB,
Microsoft SQL Server supports Transact-SQL queries against data stored in one or more SQL Server
and heterogeneous databas es without any need for s pecialized gateway server applications.
The interface required to access data in a non -local data store (s uch as the Wonderware Historian
history blocks) is provided by a "virtual" server, called an OLE DB provider. OLE DB providers allow
you to use the power of the SQL Server query processor to make linking data stored in the SQL Server
databases and from history blocks much easier and more robust. Also, the Wonderware Historian OLE
DB provider has a rich set of query capabilities.
The name of the Wonderware Historian OLE DB provider is "INS QL". The Wonderware Historian OLE
DB provider is installed during Wonderware Historian installation and then associated, or linked, with
the Microsoft SQL Server. For information on the syntax for linking the Wonderware Historian OLE DB
provider, see Link ing the Wonderware Historian OLE DB Provider to the Micros oft SQL Server on page
16.

14 Version 17.0.18000
About Data Retrieval Wonderware Historian Retrieval Guide

Note: The INSQL OLE DB provider cannot be us ed in a standalone mode.

To access Wonderware Historian historical data using OLE DB, any COM -based client application
must connect directly to the SQL Server and then specify to use the Wonderware Historian OLE DB
provider in the syntax of the query.
When you execute a query and specify the Wonderware Historian OLE DB provider in the syntax, the
Microsoft SQL Server pars er will pass the appropriat e parts of the data request to the Wonderware
Historian OLE DB provider. The Wonderware Historian OLE DB provider will then interfac e wi th the
retrieval service to locat e the data store, extract the requested information, and ret urn the data to the
Microsoft SQL Server as a rowset. Microsoft SQL Server will perform any other processing required on
the data and return the data to the client application as a result set and a set of output parameters, if
applicable.
The Wonderware Historian OLE DB provider must be present on the server running Microsoft SQL
Server. The set of Transact-SQL operations that can be used to retrieve data in the his tory blocks
depends on the capabilities of the Wonderware Historian OLE DB provider.
For more information on OLE DB, see your Microsoft documentation.

Extension Tables for History Data


Many of Historian's tables are implemented as extension tables. That is, they are logical tables that are
actually populated from dat a in history blocks.

Note: Extension tables are also called remote tables.

Data access from the history blocks is made possible by SQL Server's OLE DB provider technology.
Client applications must connect directly to the Microsoft SQL Server and then specify to use the
Wonderware Historian OLE DB provider in the syntax of the query.
The extension tables are:

History [INSQL].Runtime.dbo.History
Live [INSQL].Runtime.dbo.Live
AnalogSummaryHistory [INSQL].Runtime.dbo.AnalogSummary History
StateSummaryHistory [INSQL].Runtime.dbo.StateSummaryHistory
HistoryBlock [INSQL].Runtime.dbo.HistoryBlock
E vents [INSQL].Runtime.dbo.E vents

For more information on the history extension tables, see History Tables and Views in the Historian
Database Reference.
Legacy Process Data Extension Tables
These are legacy (backward compatible) extension tables for process data:

AnalogHistory [INSQL].Runtime.dbo.AnalogHistory
DiscreteHistory [INSQL].Runtime.dbo.DiscreteHistory
StringHistory [INSQL].Runtime.dbo.StringHistory
AnalogLive [INSQL].Runtime.dbo.AnalogLive
DiscreteLive [INSQL].Runtime.dbo.DiscreteLive
StringLive [INSQL].Runtime.dbo.StringLive

Version 17.0.18000 15
Wonderware Historian Retrieval Guide About Data Retrieval

The AnalogHistory, DiscreteHistory, StringHistory, and History tables are the only tables which are
updateable. The remaining tables are read -only.
For more information about these tables, see Backward Compatibility Entities in the Historian
Database Reference.
Legacy Event Data Extension Tables
These are legacy (backward compatible) extension tables for events:

v_AlarmE vent HistoryInternal2 [INSQL].Runtime.dbo.LegacyAlarmE ventHistory


v_AlarmHistory [INSQL].Runtime.dbo.LegacyAlarmHistory
v_AlarmHistory2 [INSQL].Runtime.dbo.LegacyAlarmHistory2
v_E vent History [INSQL].Runtime.dbo.LegacyE ventHistory
v_AlarmE vent History2 Same as v_AlarmE ventHistory Internal2

Linking the Wonderware Historian OLE DB Provider to the Microsoft


SQL Server
Because the Wonderware Historian OLE DB provider retrieves data from the history blocks and
presents it to Microsoft SQL Server as a table, it can be thought of as a type of server. The
Wonderware Historian OLE DB provider must be added to the Microsoft SQL Server as a "linked"
server before it can be used to process queries.
This linking is performed automatically during the Wonderware Historian installation. If, for some
reason, you need to re-link the Wonderware Historian OLE DB provider to the Microsoft SQL Server,
the statements for linking are as follows:

sp_addlinkedserver
@server = 'INSQL',
@srvproduct = '',
@provider = 'INSQL'
go
sp_serveroption 'INSQL','collation compatible',true
go
sp_addlinkedsrvlogin 'INSQL','TRUE',NULL,NULL,NULL
go
"INSQL" is the name of the Wonderware Historian OLE DB provider as the linked ser ver. Use this
name to specify the Wonderware Historian OLE DB provider in a query.
To perform joins between the legacy analog history tables and discrete history tables, the installation
program also creates an alias for the same Wonderware Historian OLE DB provider:

sp_addlinkedserver
@server = 'INSQLD',
@srvproduct = '',
@provider = 'INSQL'
go
sp_serveroption 'INSQLD','collation compatible',true
go
sp_addlinkedsrvlogin 'INSQLD','TRUE',NULL,NULL,NULL
go

16 Version 17.0.18000
About Data Retrieval Wonderware Historian Retrieval Guide

For example, if you want to execute a query that performs this type of join, use the normal alias in
specifying the first table (the analog history table), and use the second alias in specifying the second
table (the discrete history table, hence the "D" added to the alias name).

Wonderware Historian I/O Server


The Wonderware Historian I/O Server (aahIOS vrS vc.exe) is the interface for clients to access current
data using the SuiteLink prot ocol. The Wonderware Historian I/O Server can update items with current
values for given topics, providing "real -time" I/O Server functionality.
The Wonderware Historian I/O Server is pre -configured with a single topic, Tagname. The
Wonderware Historian I/O Server will listen for clients (such as WWClient or WindowViewer™) that are
attempting to establish a connection using the pre-configured topic. After a client connects with the
Wonderware Historian I/O Server, a "hot" link is established between the client and the Wonderware
Historian I/O Server. For more information on I/O Server addressing conventions, see I/O Server
Addressing in the Wonderware Historian Administration Guide.
For example, the Wonderware Historian I/O Server could be used by InTouch WindowViewer to
access system tag values provided by the Wonderware Historian to monitor system health. You could
configure WindowViewer to generate an alarm when abnormal behavior is detected within the
Wonderware Historian.
By default, the Wonderware Historian I/O Server runs as a Windows service and can be started and
stopped using the System Management Console. You can also monitor the Wonderware Historian I/O
Server from within the System Management Console. For more information on the System
Management Console, see About Administrative Tools in the Wonderware Historian Administration
Guide.
The Wonderware Historian I/O Server is a read-only server; clients cannot update data.
The Wonderware Historian I/O Server sends the original OPC quality as it was stored in the
Wonderware Historian. The OP C quality remains the same throughout the system, including storage,
retrieval, and the Wonderware Historian I/ O Server.

Using SELECT to Retrieve Data


The most common Wonderware Historian query is a SELECT statement:

SELECT select_list
FROM table_source
WHERE search_condition
[ GROUP BY group_by_expression ]
[ HAVING search_condition ]
[ ORDER BY order_expression [ ASC | DESC ] ]
A WHERE clause is mandatory when issuing a SELECT query against any extension table except
HistoryBlock.
There are four variations for issuing a SELECT statement to the Wonderware Historian OLE DB
provider to retrieve history data:
 Using the Four-Part Naming Convention on page 18
 Using a Wonderware Historian OLE DB Provider View on page 19
 Using the OPE NQUERY Function on page 19
 Using the OPE NROWSET Function on page 20
You should use the four-part name or a provider view to specify the extension table, whenever
possible. However, there are instances when the OPENQUE RY or OPE NR OWSET function must be
used, such as for queries on wide tables.

Version 17.0.18000 17
Wonderware Historian Retrieval Guide About Data Retrieval

For general information on creating SQL queries, see your Microsoft SQL Server documentation.

Using the Four-Part Naming Convention


The linked server name is simply a name by which the Wonderware Historian OLE DB provider is
known to the Microsoft SQL Server. In order for a query to be passed on to the Wonderware Historian
OLE DB provider, you must specify the linked server name and the extension table name as part of a
four-part naming convention.
For example, this query specifies to ret rieve data from the History extension table in the Wonderware
Historian OLE DB provider:

SELECT * FROM INSQL.Runtime.dbo.History


WHERE TagName = 'SysTimeSec'
AND DateTime >= '2001-09-12 12:59:00'
AND DateTime <= '2001-09-12 13:00:00'
The four-part naming convention is described in the following table:

Part Name Description

linked_server Linked server name. By default, INSQL.

catalog Catalog in the OLE DB dat a source that contains the


object from which you want to retrieve dat a. For
Microsoft SQL Server type databases, this is the name of
the database. To use the Wonderware Historian OLE DB
provider, the catalog name will always be "Runtime."

schema Schema in the catalog that contains the object. For


Microsoft SQL Server type databases, this is the name of
the login ID for accessing the data. To use the
Wonderware Historian OLE DB provider, the catalog
name will always be "dbo."

object_name Data object that the OLE DB provider can expose as a


rows et. For the Wonderware Historian OLE DB provider,
the object name is the name of the remote table that
contains the dat a you want to retrieve. For example, the
History table.

In the case of four-part queries, SQL Server produces the statement that is sent to the Wonderware
Historian OLE DB provider from the statement that the us er executes. Sometimes this produc ed
statement is incorrect, too complex, or lacks portions of the WHERE clause required for the
Wonderware Historian OLE DB provider to return dat a.
A typical error message when executing unsupported syntax is:

Server: Msg 7320, Level 16, State 2, Line 1


Could not execute query against OLE DB provider 'INSQL'.
[OLE/DB provider returned message: InSQL did not receive a WHERE clause from SQL
Server. If one was specified, refer to the InSQL OLE DB documentation]

18 Version 17.0.18000
About Data Retrieval Wonderware Historian Retrieval Guide

For four-part queries against non-English SQL Servers running on non -English operating systems, the
default date format might differ from the English versions. For example, for a French or German SQL
Server running on the corresponding operating system, the date/time in a four -part query must be:
yyyy-dd-mm hh:mm:ss.fff
For example:
2003-28-09 09:00:00.000
The default SQL date format is dependent on SQL Server and not on the operating system used.
However, you can modify the format using the SQL Server Convert () method. The output of this
method can be determined by the regional settings configured for the o perating system.

Using a Wonderware Historian OLE DB Provider View


Microsoft SQL Server views have been provided that will access each of the extension tables,
eliminating the need to type the four-part server name in the query. These views are named the same
as the provider table name.

Note: Backward compatibility views are named according to the v_P roviderTableName convention.

For example:

SELECT * FROM History


WHERE TagName = 'SysTimeSec'
AND DateTime >= '2001-09-12 12:59:00'
AND DateTime <= '2001-09-12 13:00:00'

Using the OPENQUERY Function


You can use the link ed server name in an OPENQUE RY function to retrieve dat a from an extension
table. The OPE NQUERY function is required for retrieving from the wide table. For ex ample:

SELECT * FROM OPENQUERY(INSQL, 'SELECT * FROM History


WHERE TagName = "SysTimeSec"
AND DateTime >= "2001-09-12 12:59:00"
AND DateTime <= "2001-09-12 13:00:00"
')
The following example retrieves data from a wide table:

SELECT * FROM OPENQUERY(INSQL, 'SELECT DateTime, SysTimeSec


FROM WideHistory
WHERE DateTime >= "2001-09-12 12:59:00"
AND DateTime <= "2001-09-12 13:00:00"
')
The OPENQUERY portion of the statement is treated as a table by SQL Server, and can also be used
in joins, views, and stored procedures. SQL Server sends the quoted statement, unchanged and as a
string, to the Wonderware Historian OLE DB provider. Consequently, only the syntax that the
Wonderware Historian OLE DB provider can parse is supported. Also, be sure that you do not exceed
the 8000 character limit for the statement. Consider the following example:

SELECT * FROM OpenQuery(INSQL, 'XYZ')


where " XY Z" is the statement to pass. You should be sure that the value of " XY Z" is not more than
8000 characters. This limit is most likely to cause a problem if you are querying many tags from a wide
table.
Also, you should supply the datetime in an OPENQUE RY stat ement in the following format:

Version 17.0.18000 19
Wonderware Historian Retrieval Guide About Data Retrieval

yyyy-mm-dd hh:mm:ss.fff
For example:
2001-01-01 09:00:00.000
You cannot use variables in an OPENQUERY statement. For more information, see Using Variables
with the Wide Table.

Using the OPENROWSET Function


The linked server name can be used as an input parameter to an OPENROWSE T function. The
OPENROWSET function sends the OLE DB provider a command to execut e. The ret urned rowset can
then be used as a table or view reference in a Transact-SQL statement. For ex ample:

SELECT * FROM OPENROWSET('INSQL',' ', 'SELECT DateTime, Quality, QualityDetail,


Value
FROM History
WHERE TagName in ("SysTimeSec")
AND DateTime >= "2001-09-12 12:59:00"
AND DateTime <= "2001-09-12 13:00:00"
')

Supported Syntax Options


The following table indicates the syntax options that are available for queries that use either the
four-part naming convention (or corresponding view name) or the OPE NQUERY function.

Syntax Element Four-Part Query OPENQUERY

ORDER BY Yes No. Does not work within the


OPENQUERY function. However, will
work if used outside of the function.

GROUP BY Yes No

TagName IN ( ..) Yes Yes

TagName LIKE '..' Yes Yes

Date and time functions (for example, Yes Yes


DateAdd)

MIN, MA X, AVG, SUM, S TDEV Yes MIN, MA X, AVG, SUM only

Sub-SELE CT wit h one normal SQL Yes, with No


Server table and one extension table restrictions

Sub-SELE CT wit h two extension tables No No

20 Version 17.0.18000
About Data Retrieval Wonderware Historian Retrieval Guide

Unsupported or Limited Syntax Options


The Wonderware Historian OLE DB provider does not support certain syntax options in queries. In
general, these limitations are due to underlying limitations in the current Micros oft SQL Server OLE DB
Provider implementation.
For general information on creating SQL queries, see your Microsoft SQL Server documentation.

No Notion of Client Context


The OLE DB provider has no notion of a client context. The OLE DB provider is entirely stateless, and
there is no persistence across queries in the same connection. This means that you must set the value
of a Wonderware Historian time domain extension (for example, cycle count) each time you exec ute a
query.
Also, the OLE DB provider cannot continuously return data (similar to a "hot" link in InTouch HMI
software). The OLE DB specification (as defined by Microsoft) does not permit a provider to return
rows to a consumer without a request from the consumer.

Limitations on W ide Tables


Wide tables do not have a fixed schema, but a schema which varies from query to query. They are
transient tables, existing for the duration of one query only. For this reas on, they must be accessed
using the OPE NQUERY function, which bypasses many of the tests and requirem ents associated with
fixed tables. Wide tables support up to 1024 columns.
For more information on wide tables, see "Wide" History Table Format in the Wonderware Historian
Database Reference.

LIKE Clause Limitations

The LIKE clause is only supported for the TagName and Value columns. The syntax " ... Value
LIKE 'a string' ... " is only supported for a string table. For example:

SELECT TagName, Value FROM History


WHERE TagName LIKE 'Sys%'
AND DateTime > '1999-05-24 14:30:00'
AND DateTime < '1999-05-24 14:32:00'

IN Clause Limitations

If you are querying analog, discrete, or string tags from the AnalogTag, DiscreteTag, or StringTag
tables (respectively), you cannot use the LIKE clause within an IN clause to condition the tagname
unless you are returning the vValue column. This restriction applies if you are using the four-part
naming convention or an extension table view.
For example:

SELECT DateTime, TagName, vValue, Quality, QualityDetail


FROM History
WHERE TagName IN (SELECT TagName FROM StringTag WHERE TagName LIKE
'SysString')
AND DateTime >='2001-06-21 16:00:00.000'
AND DateTime <='2001-06-21 16:40:00.000'
AND wwRetrievalMode = 'Delta'

Version 17.0.18000 21
Wonderware Historian Retrieval Guide About Data Retrieval

However, it is more efficient to use an INNE R REMOTE JOIN to achieve the same results. For more
information, see Using an INNER REMOTE JOIN.

OR Clause Limitations

You cannot use the OR clause to specify more than one condition for a time domain extension. For
more information, see Wonderware Historian Time Domain Extensions on page 26.

Using Joins within an OPENQUERY Function

Joins are not supported within a single OPENQUE RY statement. For example, the following query
contains an implicit join between the Tag and Live tables, and will fail:

SELECT * FROM OPENQUERY(INSQL, 'SELECT v.DateTime, v.TagName, v.Value,


t.Description
FROM Tag t, Live v
WHERE t.TagName LIKE "%Date%"
AND v.TagName = t.TagName
')
A workaround is to place the join outside of the OPENQUE RY. For example:

SELECT v.DateTime, v.TagName, v.Value, t.Description


FROM OPENQUERY(INSQL, 'SELECT DateTime, TagName, Value
FROM Live
WHERE TagName LIKE "%Date%"
') v, Tag t
WHERE v.TagName = t.TagName
Explicit joins are also not supported within OPENQUE RY. For example, the following query will fail:

SELECT * FROM OPENQUERY(INSQL, 'SELECT v.DateTime, v.TagName, v.Value, e.Unit


FROM Live v
JOIN AnalogTag t ON v.TagName = t.TagName
JOIN EngineeringUnit e ON t.EUKey = e.EUKey
WHERE v.TagName LIKE "%Date%"
')
A work-around is to place the join outside the OPE NQUERY. For example:

SELECT v.DateTime, v.TagName, v.Value, e.Unit


FROM OPENQUERY(INSQL, 'SELECT DateTime, TagName, Value FROM Live
WHERE TagName LIKE "%Date%"
') v
JOIN AnalogTag t ON v.TagName = t.TagName
JOIN EngineeringUnit e ON t.EUKey = e.EUKey
ORDER BY t.TagName
In general, use four-part syntax wherever possible. All of the previous queries are more conveniently
expressed in four-part syntax. For example, the syntax for the preceding query would be:

SELECT v.DateTime, v.TagName, v.Value, e.Unit


FROM INSQL.Runtime.dbo.History v
JOIN AnalogTag t ON v.TagName = t.TagName
JOIN EngineeringUnit e ON t.EUKey = e.EUKey
WHERE v.TagName LIKE '%Date%'

22 Version 17.0.18000
About Data Retrieval Wonderware Historian Retrieval Guide

ORDER BY t.TagName

Using Complicated Joins

You can only use simple joins bet ween SQL Server tables and the Wonderware Historian OLE DB
extension tables. Joins typically require us e of the INNE R REMOTE JOIN syntax.
For an example of the INNE R REMOTE JOIN syntax, see Using an INNE R REMOTE JOIN.

Using a Sub-SELECT with a SQL Server Table and an Extension Table

Using a sub-SELE CT with a query on a normal SQL Server table and an extension table should be
avoided; it is very inefficient due to the way SQL Server executes the query. For example:

SELECT TagName, DateTime, Value


FROM INSQL.Runtime.dbo.History
WHERE TagName IN (select TagName FROM SnapshotTag WHERE EventTagName =
'SysStatusEvent')
AND DateTime = '2001-12-20 0:00'
Instead, it is recommended that you us e the INNE R REMOTE JOIN syntax:

SELECT h.TagName, DateTime, Value


FROM SnapshotTag st INNER REMOTE JOIN INSQL.Runtime.dbo.History h
ON st.TagName = h.TagName
AND EventTagName = 'SysStatusEvent'
AND DateTime = '2001-12-20 0:00'
The results are:
TagName DateTime Value
SysPerfCPUTotal 2001-12-20 00:00:00.000 15.0
SysSpaceMain 2001-12-20 00:00:00.000 1302.0

In general, use the following pattern for INNE R REMOTE JOIN queries against the historian is:
<SQLServerTable> INNER REMOTE JOIN <HistorianExtensionTable>
For more information on INNE R REMOTE JOIN, see your Microsoft SQL Server documentation.

WHERE Clause Anomalies

In some rare cases, the SQL Server query processor truncates the WHERE clause in an attempt to
optimize the query. If you execute a query with a WHE RE clause, but an error message is returned
stating that no WHERE clause was rec eived by the SQL Server, simply add another condition clause
to the query.
For example, in the following query, the SQL Server query processor optimizes out the WHE RE
clause, because it is superfluous.

SELECT DateTime, Value, QualityDetail


FROM History
WHERE TagName LIKE '%'
A workaround is to add anot her condition clause. For example:

Version 17.0.18000 23
Wonderware Historian Retrieval Guide About Data Retrieval

SELECT DateTime, Value, QualityDetail


FROM History
WHERE TagName LIKE '%'
AND wwRetrievalMode = 'delta'

CONVERT Function Limitations

The CONVE RT function is not support ed on the vValue column in an OPENQUE RY statement. If you
are using OPENQUE RY on the History table, you must filter on the vValue column outside of the
query.
In the following example, the value of the vValue column is converted to a float. Note that no string
tags are included in the query.

SELECT * FROM OpenQuery(INSQL, 'SELECT DateTime, Quality, OPCQuality,


QualityDetail, Value, vValue, TagName
FROM History
WHERE TagName IN ("SysTimeMin", "SysPulse")
AND DateTime >= "2001-12-30 04:00:00.000"
AND DateTime <= "2001-12-30 09:00:00.000"
AND wwRetrievalMode = "Delta"
')
WHERE convert(float, vValue) = 20.0
You can also use the following formats:

WHERE convert(float, vValue) = 0


WHERE convert(float, vValue) = 0.0
WHERE convert(float, vValue) = 1.0
WHERE convert(float, vValue) = 1
WHERE convert(float, vValue) = 20
WHERE convert(float, vValue) = 2.0000e01
The following example includes a string tag and converts the vValue value to a char or varchar
datatype. All values returned can be converted to a string.

SELECT * FROM OpenQuery(INSQL, 'SELECT DateTime, Quality, OPCQuality,


QualityDetail, Value, vValue, TagName
FROM History
WHERE TagName IN ("SysString", "SysTimeMin", "SysPulse")
AND DateTime >= "2001-12-30 04:00:00.000"
AND DateTime <= "2001-12-30 09:00:00.000"
AND wwRetrievalMode = "Cyclic"
AND wwCycleCount = 300
')
WHERE convert(varchar(30), vValue) = '2001-12-30 14:00:00'
You can also use the following formats:

WHERE convert(varchar(30), vValue) = '20'


WHERE convert(varchar(30), vValue) = '1'
WHERE convert(varchar(30), vValue) = '0'

SQL Server Optimization of Complex Queries

24 Version 17.0.18000
About Data Retrieval Wonderware Historian Retrieval Guide

The SQL Server query optimizer may incorrectly parse a complex query and not send cert ain query
criteria to the Historian OLE DB provider for handling. This can caus e unexpected results for the data.
If you suspect that this is happening, use SQL Server Management Studio tools to examine the query
plan that the optimizer is using and then modify your query so that the needed criteria gets directed to
the Historian OLE DB provider.
For example, the following query will be incorrectly parsed:

SELECT GETDATE()
DECLARE @TagList TABLE (TagName nvarchar(256))
INSERT @TagList
SELECT 'SysTimeSec' UNION
SELECT 'SysPerfCPUTotal'
-- Prevent the TagName criteria from being sent to the Historian OLE DB provider
(incorrect)
SELECT DateTime, h.vValue, h.TagName
FROM History h
INNER REMOTE JOIN @TagList l
ON h.TagName = l.TagName
WHERE DateTime >= DATEADD(hour,-1,GETDATE())
AND DateTime < GETDATE()
AND wwRetrievalMode = 'AVG'
AND wwCycleCount=1
GO
To correct this issue, rewrite the query so that the tagname criteria is passed to the Historian OLE DB
provider correctly.

SELECT GETDATE()
DECLARE @TagList TABLE (TagName nvarchar(256))
INSERT @TagList
SELECT 'SysTimeSec' UNION
SELECT 'SysPerfCPUTotal'
-- Force the TagName criteria to be sent to the InSQL OLE DB Provider (correct)
SELECT DateTime, h.vValue, h.TagName
FROM @TagList l
INNER REMOTE JOIN History h
ON h.TagName = l.TagName
WHERE DateTime >= DATEADD(hour,-1,GETDATE())
AND DateTime < GETDATE()
AND wwRetrievalMode = 'AVG'
AND wwCycleCount=1
GO

Using Columns of a Variant Type with Functions

If you use a column of a variant type as the parameter for some functions, SQL Server returns a syntax
error. However, the error is not passed to the Historian OLE DB provider to return to clients.
For example, in the following query, the rounding is specified for the vValue column, which is of type
variant. The query does not work, but no error is returned by the Historian OLE DB provider.

SELECT DateTime, round(vValue, 2)


FROM History
WHERE TagName IN ('SysTimeSec')
AND DateTime = getdate()
AND wwRetrievalMode = 'Cyclic'

Version 17.0.18000 25
Wonderware Historian Retrieval Guide About Data Retrieval

Using StartDateTime in the Query Criteria

You cannot use StartDateTime in the query criteria instead of DateTime. For example, the following
query works, except that it does not apply the StartDateTime >= @Start Date claus e.

SET NOCOUNT ON
DECLARE @StartDate DateTime
DECLARE @EndDate DateTime
SET @StartDate = DateAdd(mi,-30,GetDate())
SET @EndDate = GetDate()
SET NOCOUNT OFF
SELECT History.TagName, DateTime = convert(nvarchar, DateTime, 21), Value,
vValue, StateTime, StartDateTime
FROM History
WHERE History.TagName IN ('Reactor1Level')
AND wwRetrievalMode = 'RoundTrip'
AND wwStateCalc = 'AvgContained'
AND vValue = convert(SQL_VARIANT, '1')
AND wwCycleCount = 1
AND wwTimeStampRule = 'Start'
AND wwQualityRule = 'Good'
AND wwFilter = 'ToDiscrete(5.0,>)'
AND wwVersion = 'Latest'
AND DateTime >= @StartDate
AND DateTime <= @EndDate
AND StartDateTime >= @StartDate

Comparison Statements and NULL Values

SQL Server returns an error for a query that contains a comparis on statement like 'Value > 0'
whenever a NULL is returned. Be sure that you always include 'AND Value IS NOT NULL', so that the
NULL values are filtered out.

OPENQUERY and Micr osoft Query

Microsoft Query is not able to proc ess an OPENQUE RY statement.

Wonderware Historian Time Domain Extensions


Data in the extension tables can be manipulated by using normal Transact -SQL code, as well as the
specialized SQL time domain extensions provided by the Wonderware Historian. The Wonderware
Historian extensions provide an easy way to query time-based data from the history tables. They also
provide additional functionality not support ed by Transact-SQL.
The time domain extensions are:

26 Version 17.0.18000
About Data Retrieval Wonderware Historian Retrieval Guide

 wwCycleCount  wwStateCalc
 wwE dgeDet ection  wwTimeDeadband
 wwFilter  wwTimeZone
 wwInt erpolationType  wwV alueDeadband
 wwOption  wwV ersion
 wwQualityRule  wwTimeStampRule
 wwResolution  wwV alueS elector
 wwRetrievalMode

Note: The wwP arameters and wwMaxStates parameters are reserved for future use. The
wwRowCount paramet er is still supported, but is deprecated in favor of wwCycleCount.

The extensions are implemented as "virtual" columns in the extension tables. When you query an
extension table, you can specify values for these column parameters to manipulate the dat a that will be
returned. You will need to specify any real-time extension parameters each time that you execute the
query.
For example, you could specify a value for the wwResolution column in the query so that a resolution is
applied to the returned data set:

SELECT DateTime, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND DateTime >= '2001-12-02 10:00:00'
AND DateTime <= '2001-12-02 10:02:00'
AND Value >= 50
AND wwResolution = 10
AND wwRetrievalMode = 'cyclic'
Because the extension tables provide additional functionality that is not possible in a normal SQL
Server, certain limitations apply to the Transact-SQL supported by these tables. For more information,
see Unsupported or Limited Syntax Options on page 21.
Although the Microsoft SQL Server may be configured to be case-sensitive, the values for the virtual
columns in the extension tables are always case-insensitive.

Note: You cannot use the IN clause or OR clause to specify more than one condition for a time
domain extension. For example, "wwVersion IN ('original', 'latest')" and
"wwRetrievalMode = 'Delta' OR wwVersion = 'latest'" are not support ed.

For general information on creating SQL queries, see your Microsoft SQL Server documentation.

Version 17.0.18000 27
Wonderware Historian Retrieval Guide

C HAPTER 2
Data Retrieval Options
You can use a variety of retrieval modes and options to suit different reporting needs and applications.

In This Chapter
Understanding Retrieval Modes ..................................................................................................... 29
Understanding Retrieval Options ................................................................................................... 88

Understanding Retrieval Modes


Different retrieval modes allow you to access the data stored in a Wonderware Historian in different
ways. For example, if you retrieve data for a long time period, you might want to retrieve only a few
hundred evenly spaced dat a points to minimize response time. For a shorter time period, you might
want to retrieve all values that are stored on the server to get more accurate res ults.
A Wonderware Historian with a version earlier than 9. 0 supports two ret rieval modes:
 Cyclic Retrieval on page 29
 Delta Retrieval on page 32
A Wonderware Historian with a version of 9.0 or higher supports various additional modes:
 Full Retrieval on page 37
 Interpolated Retrieval on page 39
 "Best Fit" Retrieval (see "Best Fit Retrieval" on page 43)
 Average Ret rieval on page 48
 Minimum Retrieval on page 52
 Maximum Retrieval on page 57
 Integral Retrieval on page 62
 Slope Retrieval on page 64
 Counter Retrieval on page 66
 ValueState Retrieval on page 70
A Wonderware Historian with a version of 10.0 or higher supports the following additional mode:
 RoundTrip Retrieval on page 76

Cyclic Retrieval
Cyclic retrieval is the retrieval of stored data for the given time period based on a specified cyclic
retrieval resolution, regardless of whether or not the value of the tag(s) has changed. It works with all
types of tags. Cyclic retrieval produces a virtual rowset, which may or may not correspond to the actual
data rows stored on the Wonderware Historian.

Version 17.0.18000 29
Wonderware Historian Retrieval Guide Data Retrieval Options

In cyclic retrieval, one row is returned for each "cycle boundary." You specify the number of cycles
either directly or by means of a time resolution, that is, the spacing of cycle boundaries in time. If you
specify a number of cycles, the Wonderware Historian ret urns that number of rows, evenly spaced in
time over the requested period. The cyclic resolution is calculated by dividing the requested time period
by the number of cycle boundaries. If you specify a resolution, the number of cycles is calculated by
dividing the time period by the resolution.
If no data value is actually stored at a cycle boundary, the last value before the boundary is returned.
Beginning with Wonderware System Platform 2014 R2 SP1, Historian cyclic storage rules improve the
handling of "slow rate change" data tags. Instead of delaying posts to the databas e if tag values do not
arrive in a timely manner, new rules define a cyclic timeout when the database will be updated anyway.
That timeout is typically one-half the period for the tag’s cycle storage rate or the database server’s
maximum cyclic storage timeout, whichever is shorter. The time out is controlled by a the system
parameter MaxCyclicStorageTimeout. For more information, see System Parameters in the
Wonderware Historian Administration Guide.
The default retrieval mode is cyclic for ret rieval from analog tables, including analog and state
summary tables.
Cyclic retrieval is fast and therefore consumes little server resources. However, it may not correctly
reflect the stored data because important proc ess values (gaps, spikes, etc.) might fall bet ween cycle
boundaries. For an alternative, see Best Fit Retrieval (see "Best Fit Retrieval" on page 43).

Cyclic Retrieval - How It Works

The following illustration shows how values are returned for cyclic retrieval:

Data is retrieved in cyclic mode with a start time of TC0 and an end time of TC2. The resolution has been
set in such a way that the historian returns dat a for three cycle boundaries at TC0, TC1, and TC2. Each
dot in the graphic represents an actual dat a point stored on the historian. From these points, the
following are ret urned:
 At TC0: P2, because it falls right on the cycle boundary
 At TC1: P7, because it is the last point before the cycle boundary
 At TC2: P11, for the same reason

Cyclic Retrieval - Supported Value Parameters

30 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

You can use various parameters to adjust which values are returned in c yclic retrieval mode. For more
information, see the following sections:
 Cycle Count (X Values over Equal Time Intervals) (wwCycleCount) on page 90
 Resolution (Values Spaced Every X ms) (wwResolution) on page 92
 History Version (wwVersion) on page 103
 Timestamp Rule (wwTimestampRule) on page 106, for Wonderware Historian 9.0 and above
 Qualit y Rule (wwQualit yRule) on page 111

Cyclic Retrieval - Query Example


To use the cyclic retrieval mode, set the following parameter in your query.

wwRetrievalMode = 'Cyclic'
For example, the following query returns data values for the analog tag 'ReactLevel'. If you do not
specify a wwCycleCount or wwResolution, the query will return 100 rows (the default).

SELECT DateTime, Sec = DATEPART(ss, DateTime), TagName, Value


FROM History
WHERE TagName = 'ReactLevel'
AND DateTime >= '2001-03-13 1:15:00pm'
AND DateTime <= '2001-03-13 2:15:00pm'
AND wwRetrievalMode = 'Cyclic'
The results are:

DateTime Sec TagName Value

2001-03-13 13:15:00.000 0 ReactLevel 1775.0


2001-03-13 13:15:00.000 36 ReactLevel 1260.0
2001-03-13 13:16:00.000 12 ReactLevel 1650.0
2001-03-13 13:16:00.000 49 ReactLevel 1280.0
2001-03-13 13:17:00.000 25 ReactLevel 1525.0
2001-03-13 13:18:00.000 1 ReactLevel 585.0
2001-03-13 13:18:00.000 38 ReactLevel 1400.0
2001-03-13 13:19:00.000 14 ReactLevel 650.0
2001-03-13 13:19:00.000 50 ReactLevel 2025.0
2001-03-13 13:20:00.000 27 ReactLevel 765.0
2001-03-13 13:21:00.000 3 ReactLevel 2000.0
2001-03-13 13:21:00.000 39 ReactLevel 830.0
2001-03-13 13:22:00.000 16 ReactLevel 1925.0
...

(100 row(s) affected)

Version 17.0.18000 31
Wonderware Historian Retrieval Guide Data Retrieval Options

Cyclic Retrieval - Initial Values

No special handling is done for initial values. The initial value will behave like a normal cycle boundary
at the start time. For information on initial values, see Delta Ret rieval - Initial Values on page 36.

Cyclic Retrieval - Handling NULL Values

No special handling is done for NULL values. They are returned just like any other value.

Delta Retrieval

Delta retrieval, or retrieval based on exception, is the retrieval of only the changed values for a tag(s)
for the given time int erval. That is, duplicate values are not returned. It works with all types of tags.
Delta retrieval always produces a rowset comprised of only rows that are actually stored on the
historian; that is, a delta query returns all of the physical rows in history for the specified tags, over the
specified period, minus any duplicate values. If there is no actual data point at the start time, the last
data point before the start time is returned.
Delta retrieval is the default mode for discrete and string tables and from the History table.

Delta Retrieval - How It Works

The following illustration shows how values are returned for delta retrieval:

Data is retrieved in delta mode with a start time of T1 and an end time of T2. Each dot in the graphic
represents an actual dat a point stored on the historian. From these points, the following are returned:
 P2, because there is no actual dat a point at T1
 P5, P8, P9, P10, and P11, because they repres ent changed values during the time period
For delta retrieval for replicated summary tags on a tier-2 historian, if a point with doubtful quality is
returned as the result of a value selection from an input summary point with a cont ained gap, the same
point can be returned again with good quality if the same value is selected again from the next input
summary point that has good quality.

32 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

Delta Retrieval - Supported Value Parameters

You can use various parameters to adjust which values are returned in delta retrieval mode. For more
information, see the following sections:
 Time Deadband (wwTimeDeadband) on page 96
 Value Deadband (wwValueDeadband) on page 100
 History Version (wwVersion) on page 103
 Qualit y Rule (wwQualit yRule) on page 111

Delta Retrieval - Query Examples

To use the delta retrieval mode, set the following parameter in your query.

wwRetrievalMode = 'Delta'

For examples, see the following:


 Delta Retrieval - Query 1 on page 33
 Delta Retrieval - Query 2 on page 34
 Delta Retrieval - Query 3 on page 35
 Delta Retrieval - Query 4 on page 35

Delta Retrieval - Query 1


As an example of how delta mode works, consider the following query:

SELECT TagName, DateTime, Value, QualityDetail


FROM History
WHERE TagName = 'A001'
AND DateTime >= '2009-09-12 00:20'
AND DateTime <= '2009-09-12 00:40'
AND wwRetrievalMode = 'Delta'
This query can be run against the following sample data:

Tagname DateTime Value QualityDetail


A001 2009-09-12 00:11 1.0 192
A001 2009-09-12 00:13 1.6 192
A001 2009-09-12 00:16 1.3 192

A001 2009-09-12 00:21 2.0 192


A001 2009-09-12 00:24 1.2 192
A001 2009-09-12 00:27 1.2 192
A001 2009-09-12 00:28 0.0 249
A001 2009-09-12 00:29 0.0 249
A001 2009-09-12 00:32 0.6 192

Version 17.0.18000 33
Wonderware Historian Retrieval Guide Data Retrieval Options

Tagname DateTime Value QualityDetail


A001 2009-09-12 00:35 0.0 249
A001 2009-09-12 00:37 1.5 192
A001 2009-09-12 00:43 1.3 192

A graphical representation of the data is as follows:

The results are:

Tagname DateTime Value QualityDetail

A001 2009-09-12 00:20 1.3 192


A001 2009-09-12 00:21 2.0 192
A001 2009-09-12 00:24 1.2 192
A001 2009-09-12 00:28 NULL 249
A001 2009-09-12 00:32 0.6 192
A001 2009-09-12 00:35 NULL 249
A001 2009-09-12 00:37 1.5 192

The sample data points and the res ults are mapped on the following chart. Only the data falling
between the time start and end marks at 2009 -09-12 00:20 and 2009-09-12 00:40 (shown on the chart
as dark vertical lines) are returned by the query.
Because there is no value that matches the start time, an initial value at 2009-09-12 00:20 is returned
in the results based on the value of the preceding data point at 2009-09-12 00:16. Because there is no
change in the value at 2009-09-12 00:27 from the value at 2009-09-12 00:24, the data point appears
on the chart but does not appear in the results. Similarly, the second 0.0 value at 2009-09-12 00:29 is
also excluded from the results.
You can further cont rol the number of rows ret urned by using the wwTimeDeadband,
wwV alueDeadband, and wwCycleCount extensions. The use of a cycle count returns the first number
of rows within the time range of the query. For more information, see Using wwResolution,
wwCycleCount, and wwRetrievalMode in the Same Query .
Also, the use of a time deadband and/or value deadband with delta retrieval produces differing results.
For more information, see Time Deadband (wwTimeDeadband) on page 96 and Value Deadband
(wwValueDeadband) on page 100.

Delta Retrieval - Query 2


SELECT DateTime, TagName, Value
FROM History
WHERE TagName IN ('SysTimeSec','SysTimeMin')
AND DateTime >= '2001-12-09 11:35'

34 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

AND DateTime <= '2001-12-09 11:36'


AND wwRetrievalMode = 'Delta'
The results are:

DateTime TagName Value


2001-12-09 11:35:00.000 SysTimeSec 0
2001-12-09 11:35:00.000 SysTimeMin 35
2001-12-09 11:35:01.000 SysTimeSec 1
2001-12-09 11:35:02.000 SysTimeSec 2
2001-12-09 11:35:03.000 SysTimeSec 3
2001-12-09 11:35:04.000 SysTimeSec 4
...

2001-12-09 11:35:58.000 SysTimeSec 58


2001-12-09 11:35:59.000 SysTimeSec 59
2001-12-09 11:36:00.000 SysTimeSec 0
2001-12-09 11:36:00.000 SysTimeMin 36

Delta Retrieval - Query 3


SELECT * FROM OpenQuery(INSQL,'SELECT DateTime, Value, Quality, QualityDetail
FROM AnalogHistory
WHERE TagName = "SysTimeSec"
AND wwRetrievalMode = "Delta"
AND Value = 10
AND DateTime >="2001-07-27 03:00:00.000"
AND DateTime <="2001-07-27 03:05:00.000"
')
The results are:

DateTime Value Quality QualityDetail


2001-07-27 03:00:10.000 10 0 192
2001-07-27 03:01:10.000 10 0 192
2001-07-27 03:02:10.000 10 0 192
2001-07-27 03:03:10.000 10 0 192
2001-07-27 03:04:10.000 10 0 192

Delta Retrieval - Query 4


For a delta query, if bot h a wwCycleCount and a Value comparison are specified, the query will ret urn
the first number of rows (if available) that meet the value indicated.

SELECT * FROM OpenQuery(INSQL,'SELECT DateTime, Value, Quality, QualityDetail


FROM AnalogHistory
WHERE TagName = "SysTimeSec"
AND wwRetrievalMode = "Delta"
AND Value = 20
AND wwCycleCount = 10

Version 17.0.18000 35
Wonderware Historian Retrieval Guide Data Retrieval Options

AND DateTime >="2001-07-27 03:00:00.000"


AND DateTime <="2001-07-27 03:20:00.000"
')
The results are:

DateTime Value Quality QualityDetail


2001-07-27 03:00:20.000 20 0 192
2001-07-27 03:01:20.000 20 0 192
2001-07-27 03:02:20.000 20 0 192
2001-07-27 03:03:20.000 20 0 192
2001-07-27 03:04:20.000 20 0 192
2001-07-27 03:05:20.000 20 0 192
2001-07-27 03:06:20.000 20 0 192
2001-07-27 03:07:20.000 20 0 192
2001-07-27 03:08:20.000 20 0 192
2001-07-27 03:09:20.000 20 0 192

Delta Retrieval - Initial Values


Initial values are special values that can be returned from queries that lie exactly on the query start
time, even if there is not a data point that specifically matches the specified start time. If there is not a
value exactly on the query start time, the last point before the start time will be returned wit h its
DateTime set to the query start time and its Quality set to 133. If no value exists at or prior to the query
start time, a NULL value will be ret urned at start time with QualityDetail set to 65536, OPCQuality set
to 0, and Quality set to 1.
Querying the start time in exclusive form with the > operator indicates that a value should not be
returned for the query start time if one does not exist. Querying the start time in inclusive form with the
>= operat or indic ates that an initial value should be returned.
For example, the following exclusive query statement does not return an initial value for 2009-01-01
02:00: 00.

DateTime > '2009-01-01 02:00:00'


However, the following inclusive query statement does return an initial value for 2009-01-01 02:00:00.

DateTime >= '2009-01-01 02:00:00'


No special final value is returned.

Delta Retrieval - Handling NULL Values


The initial NULL value after a non-NULL is always returned. Multiple NULL values are suppressed. The
first non-NULL after a NULL is always returned even if it is the same as the previous non-NULL value.
SELECT TagName, DateTime, Value, QualityDetail
FROM History
WHERE TagName = 'A001'
AND DateTime >= '2009-09-12 00:20'
AND DateTime <= '2009-09-12 00:40'
AND wwRetrievalMode = 'Delta'
This query can be run against the following sample data:

36 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

Tagname DateTime Value QualityDetail


A001 2009-09-12 00:17 0.8 192
A001 2009-09-12 00:24 0.0 249
A001 2009-09-12 00:27 0.0 249
A001 2009-09-12 00:28 0.5 192
A001 2009-09-12 00:31 0.0 249
A001 2009-09-12 00:33 0.0 24
A001 2009-09-12 00:35 0.0 24
A001 2009-09-12 00:36 0.5 192

The following is a graphical representation of the data:

The results are:

Tagname DateTime Value QualityDetail


A001 2009-09-12 00:20 0.8 192
A001 2009-09-12 00:24 NULL 249
A001 2009-09-12 00:28 0.5 192
A001 2009-09-12 00:31 NULL 249
A001 2009-09-12 00:36 0.5 192

The sample data points and the res ults are mapped on the following chart. Only the data falling
between the time start and end marks at 00:20 and 00:40 (shown on the chart as dark vertical lines)
are returned by the query.
Because there is no value that matches the start time, an initial value at 00:20 is returned in the results
based on the value of the preceding data point at 00:16. Because there is no change in the value at
00:27 from the value at 00:24, the data point appears on the chart but does not a ppear in the results.
Similarly, the two 0.0 values at 00:33 and 00:35 are also excluded from the results. However, the
non-NULL value at 00:36 is returned, even though it is the same as the value at 00:28, because it
represents a delta from the preceding (NULL) value at 00: 35.

Full Retrieval

In full retrieval mode, all stored data points are returned, regardless of whether a value or quality has
changed since the last value. This mode allows the same value and quality pair (or NULL value) to be
returned consecutively with their actual timestamps. It works with all types of tags.

Version 17.0.18000 37
Wonderware Historian Retrieval Guide Data Retrieval Options

By using full ret rieval in conjunction with storage without filtering (that is, no delta or cyclic storage
mode is applied at the historian), you can retrieve all values that originat ed from the plant floor dat a
source or from another application.
Full retrieval best repres ents the process measurements recorded by the Wonderware Historian.
However, it creates a higher load for the server, the network and the client system because a very
large number of records may be returned for longer time periods.
For full retrieval for replicated summary tags on a tier -2 historian, if a point with doubtful quality is
returned as the result of a value selection from an input summary point with a cont ained gap, the same
point can be returned again with good quality if the same value is selected again from the next input
summary point that has good quality.

Full Retrieval - How It Works

The following illustration shows how values are returned for full retrieval:

Data is retrieved in full mode with a start time of T1 and an end time of T2. Each dot in the graphic
represents an actual dat a point stored on the historian. From these points, the following are returned:
 P2, because there is no actual dat a point at T1
 P3 through P 12, because they represent stored data points during the time period

Full Retrieval - Supported Value Parameters

You can use various parameters to adjust which values are returned in full retrieval mode. For more
information, see the following sections:
 History Version (wwVersion) on page 103
 Qualit y Rule (wwQualit yRule) on page 111

Full Retrieval - Query Example

For example, the following query uses full retrieval mode:

SELECT DateTime, TagName, Value


FROM History
WHERE TagName IN ('SysTimeSec','SysTimeMin')
AND DateTime >= '2001-12-09 11:35'

38 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

AND DateTime <= '2001-12-09 11:36'


AND wwRetrievalMode = 'Full'

Full Retrieval - Initial Values

Full retrieval mode handles initial values the same way as delta mode. For more information on initial
values, see Delta Retrieval - Initial Values on page 36.

Interpolated Retrieval
Interpolated retrieval works like cyclic retrieval, except that interpolated values are returned if there is
no actual data point stored at the cycle boundary.
This retrieval mode is useful if you want to retrieve cyclic data for slow -changing tags. For a trend,
interpolated retrieval res ults in a smoother curve instead of a "stair-stepped" curve. This mode is also
useful if you have a slow-changing tag and a fast-changing tag and want to retrieve data for both.
Finally, some advanced applications require more evenly spaced values t han would be returned if
interpolation was not applied.
By default, interpolated retrieval uses the interpolation setting specified for the tag in the Wonderware
Historian. This means that if a tag is set to use stair-step interpolation, interpolated retri eval gives the
same results as cyclic retrieval.
Interpolation is only applied to analog tags. If you retrieve data for ot her types of tags, stair-step
interpolation is used, and the results are the same as for cyclic retrieval.
Interpolated retrieval is a bit slower than cyclic retrieval. It shares the limitations of cyclic retrieval in
that it may not accurately represent the stored process data.

Interpolated Retrieval - How It Works


The following illustration shows how the values for an analog tag that is configured for linear
interpolation are returned when using interpolated retrieval.

Data is retrieved in interpolated mode with a start time of TC 0 and an end time of TC2. The res olution
has been set in such a way that the historian returns data for three cycle boundaries at TC 0, TC1, and
TC2. P1 to P12 represent actual dat a points stored on the historian. Of these points, eleven represent
normal analog values, and one, P 7, represents a NULL value due to an I/O Server disconnect, which
causes a gap in the data between P 7 and P8.
The green points (P 2, PC1, PC2) are returned. The yellow points (P 7, P11, P12) are used to interpolate
the returned value for each cycle. The red points are considered, but not used in calculating the points
to return.

Version 17.0.18000 39
Wonderware Historian Retrieval Guide Data Retrieval Options

Because P 2 is located exactly at the query start time, it is returned at that time without the need for any
interpolation. At the following cycle boundary, point PC1 is returned, which is the NULL value
represented by P 7 shifted forward to time TC1. At the last cycle boundary, point PC2 is returned, which
has been interpolated using points P 11 and P12.

You can use various parameters to adjust which values are returned in interpolated retrieval mode. For
more information, see the following sections:
 Cycle Count (X Values over Equal Time Intervals) (wwCycleCount) on page 90
 Resolution (Values Spaced Every X ms) (wwResolution) on page 92
 History Version (wwVersion) on page 103
 Interpolation Type (wwInterpolationType) on page 104
 Timestamp Rule (wwTimestampRule) on page 106
 Qualit y Rule (wwQualit yRule) on page 111

Interpolated Retrieval - Query Examples

To use the interpolated mode, set the following parameter in your query.

wwRetrievalMode = 'Interpolated'

For examples, see the following:


 Interpolated Retrieval - Query 1 on page 40
 Interpolated Retrieval - Query 2 on page 41
 Interpolated Retrieval - Query 3 on page 42

Interpolated Retrieval - Query 1


Two analog tags and a discrete tag are retrieved from the History table, using linear int erpolation. The
start and end times are offset to show interpolation of the SysTimeMin tag. The data points at all cycle
boundaries are interpolated for the two analog tags, while the values returned for the discrete tag are
stair-stepped.

SELECT DateTime, TagName, Value, wwInterpolationType FROM History


WHERE TagName IN ('SysTimeMin', 'ReactTemp', 'SysPulse')
AND DateTime >= '2005-04-11 12:02:30'
AND DateTime <= '2005-04-11 12:06:30'
AND wwRetrievalMode = 'Interpolated'
AND wwInterpolationType = 'Linear'
AND wwResolution = 60000
The results are:

DateTime TagName Value wwInterpolationType


2005-04-11 12:02:30.000 SysTimeMin 2.5 LINEAR
2005-04-11 12:02:30.000 ReactTemp 23.2 LINEAR
2005-04-11 12:02:30.000 SysPulse 1.0 STAIRSTEP

40 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

DateTime TagName Value wwInterpolationType


2005-04-11 12:03:30.000 SysTimeMin 3.5 LINEAR
2005-04-11 12:03:30.000 ReactTemp 139.96753 LINEAR
2005-04-11 12:03:30.000 SysPulse 0.0 STAIRSTEP
2005-04-11 12:04:30.000 SysTimeMin 4.5 LINEAR
2005-04-11 12:04:30.000 ReactTemp 111.49636 LINEAR
2005-04-11 12:04:30.000 SysPulse 1.0 STAIRSTEP
2005-04-11 12:05:30.000 SysTimeMin 5.5 LINEAR
2005-04-11 12:05:30.000 ReactTemp 17.00238 LINEAR
2005-04-11 12:05:30.000 SysPulse 0.0 STAIRSTEP
2005-04-11 12:06:30.000 SysTimeMin 6.5 LINEAR
2005-04-11 12:06:30.000 ReactTemp 168.99531 LINEAR
2005-04-11 12:06:30.000 SysPulse 1.0 STAIRSTEP

Interpolated Retrieval - Query 2


If you omit the interpolation type in the query, the historian determines which interpolation type to use
for an analog tag based on the value of the Int erpolationType column in the A nalogTag table, in
conjunction with the InterpolationTy peInteger and InterpolationTypeReal system parameters.
In the following query both analog tags are set to use the system default through the AnalogTag table,
while the Int erpolationTypeInteger and InterpolationTypeReal system paramete rs are set to 0 and 1,
respectively. Because SysTimeMin is defined as a 2-byte integer and React Temp is defined as a real
we see that only rows for ReactTemp are interpolated.

SELECT DateTime, TagName, Value, wwInterpolationType FROM History


WHERE TagName IN ('SysTimeMin', 'ReactTemp', 'SysPulse')
AND DateTime >= '2005-04-11 12:02:30'
AND DateTime <= '2005-04-11 12:06:30'
AND wwRetrievalMode = 'Interpolated'
AND wwResolution = 60000
The results are:

DateTime TagName Value wwInterpolationType


2005-04-11 12:02:30.000 SysTimeMin 2.0 STAIRSTEP
2005-04-11 12:02:30.000 ReactTemp 23.2 LINEAR
2005-04-11 12:02:30.000 SysPulse 1.0 STAIRSTEP
2005-04-11 12:03:30.000 SysTimeMin 3.0 STAIRSTEP
2005-04-11 12:03:30.000 ReactTemp 139.96753 LINEAR
2005-04-11 12:03:30.000 SysPulse 0.0 STAIRSTEP
2005-04-11 12:04:30.000 SysTimeMin 4.0 STAIRSTEP
2005-04-11 12:04:30.000 ReactTemp 111.49636 LINEAR
2005-04-11 12:04:30.000 SysPulse 1.0 STAIRSTEP
2005-04-11 12:05:30.000 SysTimeMin 5.0 STAIRSTEP

Version 17.0.18000 41
Wonderware Historian Retrieval Guide Data Retrieval Options

DateTime TagName Value wwInterpolationType


2005-04-11 12:05:30.000 ReactTemp 17.00238 LINEAR
2005-04-11 12:05:30.000 SysPulse 0.0 STAIRSTEP
2005-04-11 12:06:30.000 SysTimeMin 6.0 STAIRSTEP
2005-04-11 12:06:30.000 ReactTemp 168.99531 LINEAR
2005-04-11 12:06:30.000 SysPulse 1.0 STAIRSTEP

Interpolated Retrieval - Query 3


SELECT TagName, DateTime, Value, QualityDetail, wwInterpolationType
FROM History
WHERE TagName = 'A001'
AND DateTime >= '2009-09-12 00:20'
AND DateTime <= '2009-09-12 00:40'
AND wwRetrievalMode = 'Interpolated'
AND wwResolution = '10000'

This query can be run against the following sample data:

Tagname DateTime Value QualityDetail


A001 2009-09-12 00:09 0.2 192
A001 2009-09-12 00:15 1.3 192
A001 2009-09-12 00:17 0.8 192
A001 2009-09-12 00:22 0.6 249
A001 2009-09-12 00:26 0.9 192
A001 2009-09-12 00:28 0.0 249
A001 2009-09-12 00:29 0.0 249
A001 2009-09-12 00:33 1.1 192
A001 2009-09-12 00:35 1.6 192
A001 2009-09-12 00:38 0.5 192
A001 2009-09-12 00:42 0.8 192

The following is a graphical representation of the data:

The results are:

42 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

Tagname DateTime Value QualityDetail wwInterpolationType

A001 2009-09-12 00:20 0.8 192 STAIRSTEP


A001 2009-09-12 00:30 NULL 249 STAIRSTEP
A001 2009-09-12 00:40 0.5 192 LINEAR

The sample data points and the res ults are mapped on the following chart. Only the data falling
between the time start and end marks at 00:20 and 00:40 (shown on the chart as dark vertical lines)
are returned by the query.
Because there is no value that matches the start time, an initial value at 00:20 is returned in the results
based on the preceding data point at 00:17 because the following data point at 00:22 is NULL.
Because a NULL value prec edes the 00:30 cycle boundary at 00:29, the NULL is ret urned at the cycle
boundary. The value at 00:40 is an interpolation of the dat a points at 00:38 and 00:42.

Interpolated Retrieval - Initial and Final Values

A value is ret urned at the start time and end time of the query using interpolation of the surrounding
points.

Interpolated Retrieval - Handling NULL Values

When a NULL value precedes a cycle boundary, that NULL will be returned at the cyc le boundary.
If a valid value precedes a cycle boundary, but is followed by a NULL value after the cycle boundary,
no interpolation will be used and wwInterpolationType will be set to S TAIRS TEP for that value.

Best Fit Retrieval

For the " best fit" retrieval mode, the total time for the query is divided int o even sub -periods, and then
up to five values are returned for each sub-period:
 First value in the period
 Last value in the period
 Minimum value in the period, with its actual time
 Maximum value in the period, with its actual time
 The first "exception" in the period (non-Good quality)

Version 17.0.18000 43
Wonderware Historian Retrieval Guide Data Retrieval Options

"Best fit" retrieval allows for a compromise bet ween delta retrieval and cyclic retrieval. For example,
delta ret rieval can accurately represent a process over a long period of time, as shown in the following
trend. However, to achieve this represent ation, a large number of data values must be returned.

If cyclic retrieval is used to retrieve the data, the retrieval is much more efficient, because fewer values
are returned. However, the representation is not as accurate, as the following trend shows.

44 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

"Best fit" retrieval allows for faster retrieval, as typically achieved by using cyclic retrieval , plus the
better represent ation typically achieved by using delta retrieval. This is shown in the following trend.

For example, for one week of five-second data, 120,960 values would be returned for delta retrieval,
versus around 300 values for best-fit retrieval.
Best-fit retrieval uses retrieval cycles, but it is not a true cyclic mode. Apart from the initial value, it only
returns actual delta points. For example, if one point is both the first value and the minimum value in a
cycle, it is returned only one time. In a cycle where a tag has no points, nothing is returned.
As in cyclic retrieval, the number of cycles is based on the specified resolution or cycle count.
However, the number of values returned is likely to be more than one per cycle.
All points are returned in chronological order. If multiple points are to be ret urned for a particular
timestamp, then those points are returned in the order in which the corresponding tags were specified
in the query.
The best-fit algorithm is only applied to analog and analog summary tags. For all other tags, delta
results are returned.

Best Fit Retrieval - How It Works

The following illustration shows how the best-fit algorit hm selects points for an analog tag.

Version 17.0.18000 45
Wonderware Historian Retrieval Guide Data Retrieval Options

Data is retrieved in best-fit mode with a start time of TC0 and an end time of TC2. The resolution has
been set in such a way that the historian returns data for two complet e cycles starting at T C0 and TC1
and an incomplete cycle starting at TC2. P1 to P 12 represent actual dat a points stored on the historian.
Of these points, eleven represent normal analog values, and one, P 7, represents a NULL value due to
an I/O Server disconnect, which causes a gap in th e data between P 7 and P8.
Because P 2 is located exactly at the start time, no initial value needs to be interpolated at the start time.
Therefore, point P 1 is not considered at all. All other points are considered, but only the points
indicated by green markers on the graph are returned.
From the first cycle, four points are returned:
 P2 as the initial value of the query, as well as the first value in the cycle
 P4 as the minimum value in the cycle
 P6 as both the maximum value and the last value in the cycle
 P7 as the first (and only) occurring exception in the cycle
From the second cycle, three points are returned:
 P8 as the first value in the cycle
 P9 as the maximum value in the cycle
 P11 as both the minimum value and the last value in the cycle
 As no exception occurs in the second cycle, none is returned.
Because the tag does not have a point exactly at the query end time, where an incomplete third cycle
starts, the end value P C2 is interpolated between P 11 and P12, assuming that linear interpolation is used.

Best Fit Retrieval - Supported Value Parameters

You can use various parameters to adjust which values are returned in best -fit retrieval mode. For
more information, see the following sections:
 Cycle Count (X Values over Equal Time Intervals) (wwCycleCount) on page 90
 Resolution (Values Spaced Every X ms) (wwResolution) on page 92
 History Version (wwVersion) on page 103
 Interpolation Type (wwInterpolationType) on page 104
 Qualit y Rule (wwQualit yRule) on page 111

Best Fit Retrieval - Query Example


To use the best fit retrieval mode, set the following parameter in your query.

wwRetrievalMode = 'BestFit'
For example, an analog tag is retrieved over a five-minute period using the best-fit retrieval mode. The
wwResolution parameter is set to 60000, thus specifying five 1-minute cycles. Within each cycle, the
retrieval sub-system returns the first, minimum, maximum, and last data points. There are no exception
(NULL) points in the time period. Notice how the points at the query start time and at the query end
time are interpolated, while all other points are actual delta points.

SELECT DateTime, TagName, CONVERT(DECIMAL(10, 1), Value) AS Value,


wwInterpolationType AS IT FROM History
WHERE TagName = 'ReactTemp'

46 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

AND DateTime >= '2005-04-11 12:15:00'


AND DateTime <= '2005-04-11 12:20:00'
AND wwRetrievalMode = 'BestFit'
AND wwResolution = 60000
The results are:

DateTime TagName Value IT


(initial, first, 2005-04-11 12:15:00.000 ReactTemp 40.7 LINEAR
min)
(max in interval 2005-04-11 12:15:38.793 ReactTemp 196.0 STAIRSTEP
1)
(last in interval 2005-04-11 12:15:58.810 ReactTemp 159.2 STAIRSTEP
1)
(first, max in 2005-04-11 12:16:00.013 ReactTemp 156.9 STAIRSTEP
interval 2)
(last, min in 2005-04-11 12:16:58.857 ReactTemp 16.3 STAIRSTEP
interval 2)
(first, min in 2005-04-11 12:17:00.060 ReactTemp 14.0 STAIRSTEP
interval 3)
(last, max in 2005-04-11 12:17:58.793 ReactTemp 151.0 STAIRSTEP
interval 3)
(first in 2005-04-11 12:18:00.107 ReactTemp 156.0 STAIRSTEP
interval 4)
(max in interval 2005-04-11 12:18:10.057 ReactTemp 196.0 STAIRSTEP
4)
(last, min in 2005-04-11 12:18:58.837 ReactTemp 106.3 STAIRSTEP
interval 4)
(first, max in 2005-04-11 12:19:00.040 ReactTemp 104.0 STAIRSTEP
interval 5)
(min in interval 2005-04-11 12:19:31.320 ReactTemp 14.0 STAIRSTEP
5)
(last in interval 2005-04-11 12:19:58.773 ReactTemp 26.0 STAIRSTEP
5)
(end bounding 2005-04-11 12:20:00.000 ReactTemp 30.7 LINEAR
value)

Best Fit Retrieval - Initial and Final Values

A point will be returned at the query start time and the query end time for each tag queried, if a point
exists for that tag at or after the end time of the query. The values of the initial and final points will be
determined by interpolating the points prec eding and following the query start or query end time.
Standard interpolation rules will be used to return the initial and final values. For more information, see
Interpolated Retrieval on page 39.

Version 17.0.18000 47
Wonderware Historian Retrieval Guide Data Retrieval Options

Best Fit Retrieval - Handling NULL Values

When any of the four good points are returned from a cycle that contains gaps or from an incomplete
cycle with the query end time located inside of the calculation cycle the quality detail of each of the
non-null points returned is modified to alert the us er to this fact. This is done by performing a logical
OR operation of the value 4096, which means partial cycle, onto the existing quality detail. (This is the
delta point equivalent to the use of PercentGood for cyclic.)

Average Retrieval

For the time-weight ed average (in short: "average") retrieval mode, a time-weighted average algorit hm
is used to calculate the value to be returned for each retrieval cycle.
For a statistical average, the actual dat a values are used to calculat e the average. The average is the
sum of the data values divided by the number of data values. For the following data values, the
statistical average is computed as:
(P1 + P 2 + P3 + P4) / 4) = Average

For a time-weighted average, values are multiplied by the time difference between the points to
determine the time-weighted value. Therefore, the longer a tag had a particular value, the more weight
that value holds in the overall average. The overall average is determined by adding all of the
time-weight ed values and then dividing that number by the total amount of time.
Which values are weighted depends on the interpolation setting of the tag. For a tag that uses linear
interpolation, the midpoints between values are weight ed. For a tag that uses stair-step interpolation,
the earlier of two values is weighted.
For the following dat a values of a tag that uses linear interpolation, the time-weighted average is
computed as:

48 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

(((P1 + P2) / 2) x (T2 - T1)) + (((P 2 + P3) / 2) x (T3 - T2)) + (((P 3 + P4) / 2) x (T4 - T3 )) / (T4 - T1) =
A verage

If the same tag uses stair-step interpolation, the time-weighted average is:
((P1 x (T2 - T1)) + (P 2 x (T3 - T2)) + (P 3 x (T4 - T3 ))) / (T4 - T1) = A verage
The SQL Server AVG aggregate is a simple statistical average. Using the average ret rieval mode wit h
a cycle count of 1 ret urns data much faster than the AVG aggregate, and us ually more accurat ely due
to the time weighting. The E vent subsystem also returns a simple statistical average.
A verage retrieval ret urns one row for each tag in the query for each cycle. The number of cycles is
based on the specified resolution or cycle count.
The time-weighted average algorithm is only applied to analog and analog summary tags. If you us e
average retrieval with other tags, the results are the same as when using regular cyclic retrieval.

Average Retrieval - How It Works

The following illustration shows how the time -weighted average is calculated for an analog tag that
uses linear interpolation.

Version 17.0.18000 49
Wonderware Historian Retrieval Guide Data Retrieval Options

Data is retrieved in average mode with a start time of TC0 and an end time of TC2. The resolution has
been set in such a way that the historian returns data for two complet e cycles starting at T C0 and TC1
and an incomplete cycle starting at TC2. P1 to P 9 represent actual data points stored on the historian. Of
these points, eight represent normal analog values, and one, P 5, represents a NULL due to an I/O
Server disconnect, which causes a gap in the data between P 5 and P 6. Assume that the query calls for
timestamping at the end of the cycle.
Results are calculated as follows:
 The "initial value" returned at the query start time (TC0) is the time-weighted average of the points
in the last cycle preceding TC0.
 The value returned at TC1 is the time-weighted average of the points in the cycle starting at TC0.
 The value returned at the query end time (TC2) is the time-weighted average of the points in the
cycle starting at TC1.
To understand how the time-weighted average is calculated, obs erve the last cycle as an example.
First, the area under the curve must be calculated. This curve is indicated by the red line through P 6,
P7, P8 and P C2, where P C2 represents the interpolated value at time TC2 using points P 8 and P 9. The
data gap caused by the I/O Server disconnect does not contribute anything to this area. If a quality rule
of "good" has been specified, then points with doubt ful quality will not contribute anything to the area,
either.
To understand how the area is calculated, consider points P 6 and P 7. The area contribution between
these two points is calculated by multiplying the arithmetic average of value P 6 and value P 7 by the
time difference between the two points. The formula is:
((P6 + P7) / 2) x (T7 - T6 )
When the area for the whole cycle has been calculated, the time-weighted average is calculated by
dividing that area by the cycle time, less any periods within the cycle that did not contribut e anything to
the area calculation. The result is returned at the cycle end time.
If you take a closer look at points P 4 and P5 in the example, you can see that the red line through point
P4 is parallel to the x-axis. This is because P 5 represents a NULL, which cannot be used to calculate
an arithmetic average. Instead, the value P 4 is used for the whole time period between points P 4 and
P5.
The area calculation is signed. If the arithmetic average between two points is negative, then the
contribution to the area is negative.

Average Retrieval - Supported Value Parameters

You can use various parameters to adjust which values are returned in average retrieval mode. For
more information, see the following sections:
 Cycle Count (X Values over Equal Time Intervals) (wwCycleCount) on page 90
 Resolution (Values Spaced Every X ms) (wwResolution) on page 92
 History Version (wwVersion) on page 103
 Interpolation Type (wwInterpolationType) on page 104
 Timestamp Rule (wwTimestampRule) on page 106
 Qualit y Rule (wwQualit yRule) on page 111

Average Retrieval - Query Examples

50 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

To use the average mode, set the following parameter in your query.

wwRetrievalMode = 'Average'

For examples, see the following:


 Average Ret rieval - Query 1 on page 51
 Average Ret rieval - Query 2 on page 52
For an additional ex ample, see Querying Aggregat e Data in Different Ways.

Average Retrieval - Query 1


The time-weighted average is computed for each of five 1-minute long cycles.
Note that the wwTimeStampRule parameter is set to "Start" in the query. This means that the value
stamped at 11:18:00.000 repres ents the average for the interval 11:18 to 11:19, the value stamped at
11:19: 00.000 represents the average for the int erval 11:19 to 11: 20, and so on. If no timestamp rule is
specified in the query, then the default setting in the TimeStampRule system parameter is used.
In the first cycle there are no points, so a NULL is returned. In the second cycle value points are found
covering 77.72 perc ent of the time as returned in Perc entGood. This means that the ret urned average
is calculated based on 77.72 percent of the cycle time. Because the same OP CQuality is not found for
all the points in the cycle, OPCQuality is set to Doubt ful. In the remaining three cycles, only good
points occur, all with an OPCQuality of 192.
Because no quality rule is specified in the query using the wwQualityRule paramet er, the query uses
the default as specified by the QualityRule system parameter. If a quality rule of Extended is specified,
any point stored with doubtful OPCQuality will be used to calculate the average, and the point time will
therefore be included in the calculation of PercentGood.

SELECT DateTime, TagName, CONVERT(DECIMAL(10, 2), Value) AS Value, OPCQuality,


PercentGood FROM History
WHERE TagName = 'ReactTemp'
AND DateTime >= '2005-04-11 11:18:00'
AND DateTime < '2005-04-11 11:23:00'
AND wwRetrievalMode = 'Average'
AND wwCycleCount = 5
AND wwTimeStampRule = 'Start'
The results are:

DateTime TagName Value OPCQuality PercentGood


(cycle 1) 2005-04-11 ReactTemp NULL 0 0.0
11:18:00.000
(cycle 2) 2005-04-11 ReactTemp 70.00 64 77.72
11:19:00.000
(cycle 3) 2005-04-11 ReactTemp 153.99 192 100.0
11:20:00.000
(cycle 4) 2005-04-11 ReactTemp 34.31 192 100.0
11:21:00.000
(cycle 5) 2005-04-11 ReactTemp 134.75 192 100.0
11:22:00.000

Version 17.0.18000 51
Wonderware Historian Retrieval Guide Data Retrieval Options

Average Retrieval - Query 2


This query demonstrates the use of the average retrieval mode in a wide query. Time-weighted
average values are returned for the analog tags React Temp and ReactLevel, while regular cyclic
points are returned for the discrete tag, WaterValve.

SELECT * FROM OpenQuery(INSQL,


'SELECT DateTime, ReactTemp, ReactLevel, WaterValve FROM WideHistory
WHERE DateTime >= "2004-06-07 08:00"
AND DateTime < "2004-06-07 08:05"
AND wwRetrievalMode = "Average"
AND wwCycleCount = 5
')
The results are:

DateTime ReactTemp ReactLevel WaterValve


2004-06-07 08:00:00.000 47.71621 1676.69716 1
2004-06-07 08:01:00.000 157.28076 1370.88097 0
2004-06-07 08:02:00.000 41.33734 797.67296 1

2004-06-07 08:03:00.000 122.99525 1921.66771 0


2004-06-07 08:04:00.000 105.28866 606.40488 1

Average Retrieval - Initial and Final Values

If wwTimeStampRule = END, the initial value is calculated by performing an average calculation on the
cycle leading up to the query start time. No special handling is done for the final value.
If wwTimeStampRule = STA RT, the final value is calculated by pe rforming an average calculation on
the cycle following the query end time. No special handling is done for the initial value.

Average Retrieval - Handling NULL Values

Gaps introduced by NULL values are not included in the average calculations. The average only
considers the time ranges with good values. TimeGood indicates the total time per cycle that the tags
value was good.

Minimum Retrieval
The minimum value retrieval mode returns the minimum value from the actual data values within a
retrieval cycle. If there are no actual data points stored on the historian for a given cycle, nothing is
returned. NULL is returned if the cycle contains one or more NULL values.
As in cyclic retrieval, the number of cycles is based on the specified resolution or cycle count.
However, minimum retrieval is not a true cyclic mode. Apart from the initial value, all points returned
are delta points.
Minimum retrieval only works with analog tags. For all other tags, normal delta results are returned.
All returned values are in chronological order. If multiple points are to be ret urned for a particular
timestamp, they are returned in the order in which the tags were specified in the query. If the minimum
value occurs several times in a cycle, the minimum value with the earliest timestamp is returned.

52 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

The minimum ret rieval mode must use the "<=" operator for the ending date/time.
Using the minimum retrieval mode with a cycle count of 1 returns the same results as the SQL Server
MIN aggregate; however, the data is returned much faster.

Minimum Retrieval - How It Works

The following illustration shows how the minimum value is selected for an analog tag.

This example has a start time of TC0 and an end time of TC2. The resolution has been set in such a way
that the historian returns dat a for two complete cycles starting at TC0 and TC1, a "phantom" cycle
starting at TCP, and an incomplete cycle starting at TC2. The phantom cycle has the same duration as
the first cycle in the query period, extending back in time from the query start time.
For the queried tag, a total of 18 points are found throughout the cycles, represented by the markers P 1
through P 18. Of these points, 17 represent normal analog values. The point P 13 represents a NULL due
to an I/O Server disconnect, which causes a gap in the data between P 13 and P 14.
The minimum value for the "phantom" cycle starting at TCP is returned as the initial value at TC0. Point
P18 is not considered at all because it is outside of the query time frame. All other points are
considered, but only the points indicated by green markers on the graph are returned (P 10, P13, and
P17).
In total, four points are returned:
 P4 as the minimum value of the "phantom" cycle and the initial point
 P10 as the minimum value in the first cycle
 P13 as the first and only exception occurring in the first cycle
 P17 as the minimum value in the second cycle
No points are returned for the incomplete third cycle starting at the query end time, becaus e the tag
does not have a point exactly at that time.
If the minimum value of the first cycle is located exactly at the query start time, both this value and the
minimum value of the phantom cycle are returned.

Minimum Retrieval - Supported Value Parameters

You can use various parameters to adjust which values are returned in minimum retrieval mode. For
more information, see the following sections:
 Cycle Count (X Values over Equal Time Intervals) (wwCycleCount) on page 90

Version 17.0.18000 53
Wonderware Historian Retrieval Guide Data Retrieval Options

 Resolution (Values Spaced Every X ms) (wwR esolution) on page 92


 History Version (wwVersion) on page 103
 Qualit y Rule (wwQualit yRule) on page 111

Minimum Retrieval - Query Examples

To use the minimum mode, set the following parameter in your query:

wwRetrievalMode = 'Min'
or

wwRetrievalMode = 'Minimum'

For examples, see the following:


 Minimum Retrieval - Query 1 on page 54
 Minimum Retrieval - Query 2 on page 55
 Minimum Retrieval - Query 3 on page 55

Minimum Retrieval - Query 1


In this example, an analog tag is retrieved over a five minute period, using the minimum retrieval mode.
Because the wwResolution parameter is set to 60000, each cycle is exactly one minute long. The
minimum data value is returned from each of these cycles .

SELECT DateTime, TagName, CONVERT(DECIMAL(10, 2), Value) AS Value FROM History


WHERE TagName = 'ReactTemp'
AND DateTime >= '2005-04-11 11:21:00'
AND DateTime <= '2005-04-11 11:26:00'
AND wwRetrievalMode = 'Minimum'
AND wwResolution = 60000
The initial value at the query start time is the minimum value found in the phantom cycle before the
start time of the query.
The results are:

DateTime TagName Value


(phantom cycle) 2005-04-11 11:21:00.000 ReactTemp 104.00
(cycle 1) 2005-04-11 11:21:30.837 ReactTemp 14.00
(cycle 2) 2005-04-11 11:22:00.897 ReactTemp 36.00
(cycle 3) 2005-04-11 11:23:59.567 ReactTemp 18.60
(cycle 4) 2005-04-11 11:24:02.083 ReactTemp 14.00
(cycle 5) 2005-04-11 11:25:59.550 ReactTemp 108.60

54 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

Minimum Retrieval - Query 2


In this example, the minimum retrieval mode is used in a manner equivalent to using the SQL Server
MIN aggregate. Note that the cycle producing the result is the five-minut e phantom cycle just before
the query start time.

SELECT TOP 1 DateTime, TagName, CONVERT(DECIMAL(10, 2), Value) AS Value FROM


History
WHERE TagName = 'ReactTemp'
AND DateTime >= '2005-04-11 11:31:00'
AND DateTime <= '2005-04-11 11:31:00'
AND wwRetrievalMode = 'Minimum'
AND wwResolution = 300000
The results are:

DateTime TagName Value


(phantom cycle) 2005-04-11 11:31:00.000 ReactTemp 14.00

Minimum Retrieval - Query 3


This example shows how the minimum retrieval mode marks the QualityDetail column to indicate that a
minimum value is returned based on an incomplete cycle. In this case, an incomplete cycle is a cycle
that either contained periods with no values stored or a cycle that was cut short becaus e the query end
time was located inside the cycle. All values returned for the QualityDetail column are documented in
the QualityMap table in the Runtime database.

SELECT DateTime, TagName, Value, QualityDetail FROM History


WHERE TagName = 'SysTimeSec'
AND DateTime >= '2005-04-11 11:18:50'
AND DateTime <= '2005-04-11 11:20:50'
AND wwRetrievalMode = 'Minimum'
AND wwResolution = 60000
The results are:

DateTime TagName Value QualityDetail


(phantom cycle) 2005-04-11 SysTimeSec NULL 65536
11:18:50.000
(cycle 1) 2005-04-11 SysTimeSec 13.0 4140
11:19:13.000
(cycle 2) 2005-04-11 SysTimeSec 0.0 192
11:20:00.000
(cycle 3) 2005-04-11 SysTimeSec 50.0 4288
11:20:50.000

Minimum Retrieval - Initial and Final Values

Version 17.0.18000 55
Wonderware Historian Retrieval Guide Data Retrieval Options

For analog tags, the minimum value of the tag in the cycle leading up to the query start time is returned
with its timestamp changed to the query start time. If there is no point exactly at the "phant om" cycle
start time, the point leading up to the phantom cycle is also considered for the minimum calculation.(No
adjustments are made to the quality of the initial point even though the timestamp may have been
altered.) Apart from the initial value, all points returned are delta points. (For more information on initial
values, see Delta Retrieval - Initial Values on page 36.)
If a point occurs exactly on the query end time, that point will be returned with the partial cycle bit,
4096, set in quality detail. If there is more than one such point, only the first point will be returned.

Minimum Retrieval - Handling NULL Values and Incomplete Cycles

The first NULL value in a cycle is returned.


When a minimum value is returned from a cycle that contains gaps (including a gap extended from the
previous cycle) or from an incomplete cycle with the query end time loc ated inside of the calculation
cycle, the point’s quality detail is modified to flag this. This is done by performing a logical OR
operation of the value 4096, which indicates a partial cycle, onto the existing quality detail.
As an example of how minimum retrieval mode handles NULLs, consider the following query:

SELECT TagName, DateTime, Value, QualityDetail


FROM History
WHERE TagName = 'A001'
AND DateTime >= '2009-09-12 00:20'
AND DateTime <= '2009-09-12 00:40'
AND wwResolution = 10000
AND wwRetrievalMode = 'Minimum'
This query can be run against the following sample data:

Tagname DateTime Value QualityDetail


A001 2009-09-12 00:09 0.2 192
A001 2009-09-12 00:15 1.3 192
A001 2009-09-12 00:17 0.8 192
A001 2009-09-12 00:22 0.5 192
A001 2009-09-12 00:26 0.9 192
A001 2009-09-12 00:28 0.0 249
A001 2009-09-12 00:29 0.0 249
A001 2009-09-12 00:33 1.1 192
A001 2009-09-12 00:35 1.6 192
A001 2009-09-12 00:38 0.5 192
A001 2009-09-12 00:42 0.8 192

56 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

The following is a graphical representation of the data:

The results are:

Tagname DateTime Value QualityDetail


A001 2009-09-12 00:20 0.2 192
A001 2009-09-12 00:22 0.5 4288
A001 2009-09-12 00:28 NULL 249
A001 2009-09-12 00:38 0.5 4288

The sample data points and the res ults are mapped on the following chart. Only the data falling
between the time start and end marks at 00:20 and 00:40 (shown on the chart as dark vertical lines)
are returned by the query. The resolution is set at 10,000 milliseconds.
Because there is no value that matches the start time, an initial value at 00:20 is returned based on the
minimum value of the preceding cycle, which is the data point at 00:09. In the two subsequent cycles,
the minimum values are at 00:22 and 00:38. The quality for these two values is set to 4288 (4096 +
192). The remaining data points are excluded becaus e they are not minimums. In addition, the first
NULL at 00: 28 is included, but the second NULL (at 00:29) is not.

Maximum Retrieval
The maximum value retrieval mode returns the maximum value from the actual dat a values within a
retrieval cycle. If there are no actual data points stored on the historian for a given cycle, nothing is
returned. NULL is returned if the cycle contains one or more NULL values.
As in cyclic retrieval, the number of cycles is based on the specified resolution or cycle count.
However, maximum ret rieval is not a true cyclic mode. Apart from the initial value, all points returned
are delta points.
Maximum ret rieval only works with analog tags. For all ot her tags, normal delta results are returned.
All returned values are in chronological order. If multiple points are to be ret urned for a particular
timestamp, they are returned in the order in which the tags were specified in the query. If the maximum
value occurs several times in a cycle, the maximum value with the earliest timestamp is returned.
The maximum retrieval mode must use the "<=" operat or for the ending date/time.
Using the maximum ret rieval mode wit h a cycle count of 1 returns the same res ults as the SQL Server
MA X aggregate; however, the data is returned much faster.

Maximum Retrieval - How It Works

Version 17.0.18000 57
Wonderware Historian Retrieval Guide Data Retrieval Options

The following illustration shows how the maximum value is selected for an analog tag.

This example has a start time of TC0 and an end time of TC2. The resolution has been set in such a way
that the historian returns dat a for two complete cycles starting at TC0 and TC1, a "phantom" cycle
starting at TCP, and an incomplete cycle starting at TC2. The phantom cycle has the same duration as
the first cycle in the query period, extending back in time from the query start time.
For the queried tag, a total of 18 points are found throughout the cycles, represented by the markers P 1
through P 18. Of these points, 17 represent normal analog values. The point P 13 represents a NULL due
to an I/O Server disconnect, which causes a gap in the data between P 13 and P 14.
The maximum value for the "phantom" cycle starting at TCP is returned as the initial value at TC0. Point
P18 is not considered at all because it is outside of the query time frame. All other points are
considered, but only the points indicated by green markers on the graph are returned (P 12, P13, and
P15).
In total, four points are returned:
 P6 as the maximum value of the "phantom" cycle and the initial point
 P12 as the maximum value in the first cycle
 P13 as the first and only exception occurring in the first cycle
 P15 as the maximum value in the second cycle
No points are returned for the incomplete third cycle starting at the query end time, becaus e the tag
does not have a point exactly at that time.
If the maximum value of the first cycle is located exactly at the query start time, this value and the
maximum value of the phantom cycle are returned.

Maximum Retrieval - Supported Value Parameters

You can use various parameters to adjust which values are returned in maximum retrieval mode. For
more information, see the following sections:
 Cycle Count (X Values over Equal Time Intervals) (wwCycleCount) on page 90
 Resolution (Values Spaced Every X ms) (wwResolution) on page 92
 History Version (wwVersion) on page 103
 Qualit y Rule (wwQualit yRule) on page 111

Maximum Retrieval - Query Examples

58 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

To use the maximum mode, set the following parameter in your query:

wwRetrievalMode = 'Max'
or
wwRetrievalMode = 'Maximum'

For examples, see the following:


 Maximum Retrieval - Query 1 on page 59
 Maximum Retrieval - Query 2 on page 59
 Maximum Retrieval - Query 3 on page 60

Maximum Retrieval - Query 1


In this example, an analog tag is retrieved over a five -minute period, using the maximum retrieval
mode. Because the wwResolution parameter is set to 60000, each cycle is exactly one minute long.
The maximum data value is returned from eac h of these cycles .

SELECT DateTime, TagName, CONVERT(DECIMAL(10, 2), Value) AS Value FROM History


WHERE TagName = 'ReactTemp'
AND DateTime >= '2005-04-11 11:21:00'
AND DateTime <= '2005-04-11 11:26:00'
AND wwRetrievalMode = 'Maximum'
AND wwResolution = 60000
The initial value at the query start time is the maximum value found in the phantom cycle before the
start time of the query.
The results are:
Cycle DateTime TagName Value
(phantom cycle) 2005-04-11 11:21:00.000 ReactTemp 196.00
(cycle 1) 2005-04-11 11:21:00.853 ReactTemp 101.70
(cycle 2) 2005-04-11 11:22:40.837 ReactTemp 196.00
(cycle 3) 2005-04-11 11:23:00.833 ReactTemp 159.20
(cycle 4) 2005-04-11 11:24:59.613 ReactTemp 146.00
(cycle 5) 2005-04-11 11:25:12.083 ReactTemp 196.00

Maximum Retrieval - Query 2


In this example, the maximum retrieval mode is used in a manner equivalent to using the SQL Server
MIN aggregate. Note that the cycle producing the result is the five-minut e phantom cycle just before
the query start time.

SELECT TOP 1 DateTime, TagName, CONVERT(DECIMAL(10, 2), Value) AS Value FROM


History
WHERE TagName = 'ReactTemp'
AND DateTime >= '2005-04-11 11:31:00'
AND DateTime <= '2005-04-11 11:31:00'
AND wwRetrievalMode = 'Maximum'
AND wwResolution = 300000
The results are:

Version 17.0.18000 59
Wonderware Historian Retrieval Guide Data Retrieval Options

DateTime TagName Value


(phantom cycle) 2005-04-11 11:31:00.000 ReactTemp 196.00

Maximum Retrieval - Query 3


This example shows how the maximum ret rieval mode marks the QualityDetail column to indicate that
a maximum value is returned based on an inc omplet e cycle. In this case, an incomplete cycle is a
cycle that either contained periods with no values stored or a cycle that was cut short because the
query end time was located inside the cycle. All values returned for the QualityDetail column are
documented in the QualityMap table in the Runtime database.

SELECT DateTime, TagName, Value, QualityDetail FROM History


WHERE TagName = 'SysTimeSec'
AND DateTime >= '2005-04-11 11:19:10'
AND DateTime <= '2005-04-11 11:21:10'
AND wwRetrievalMode = 'Maximum'
AND wwResolution = 60000
The results are:

DateTime TagName Value QualityDetail


(phantom cycle) 2005-04-11 SysTimeSec NULL 65536
11:19:10.000
(cycle 1) 2005-04-11 SysTimeSec 59 4288
11:19:59.000
(cycle 2) 2005-04-11 SysTimeSec 59 192
11:20:59.000
(cycle 3) 2005-04-11 SysTimeSec 10 4288
11:21:10.000

Maximum Retrieval - Initial and Final Values

For analog tags, the maximum value of the tag in the cycle leading up to the query start time is
returned with its timestamp changed to the query start time. If there is no point exactly at the phantom
cycle start time, the point leading up to the phantom cycle is also considered for the maximum
calculation. No adjustments are made to the quality of the initial point even though the timestamp may
have been alt ered. Apart from the initial value, all points returned are delt a points. (For more
information on initial values, see Determining Cycle Boundaries on page 139.)
If a point occurs exactly on the query end time, that point is returned wit h the partial cycle bit, 4096, set
in quality detail. If there is more than one such point, only the first point is returned.

Maximum Retrieval - Handling NULL Values and Incomplete Cycles

The first NULL value in a cycle is returned.


When a maximum value is returned from a cycle that contains gaps (including a gap extended from the
previous cycle) or from an incomplete cycle with the query end time loc ated inside of the calculation
cycle, the point’s quality detail is modified to flag this. This is done by performing a logical OR
operation of the value 4096, which indicates a partial cycle, onto the existing quality detail.

60 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

As an example of how maximum retrieval mode handles NULLs, consider the following query:

SELECT TagName, DateTime, Value, QualityDetail


FROM History
WHERE TagName = 'A001'
AND DateTime >= '2009-09-12 00:20'
AND DateTime <= '2009-09-12 00:40'
AND wwResolution = 10000
AND wwRetrievalMode = 'Maximum'
If you run this query against the following sample data:

Tagname DateTime Value QualityDetail


A001 2009-09-12 00:09 0.2 192
A001 2009-09-12 00:15 1.3 192
A001 2009-09-12 00:17 0.8 192
A001 2009-09-12 00:22 0.5 192
A001 2009-09-12 00:26 0.9 192
A001 2009-09-12 00:28 0.0 249
A001 2009-09-12 00:29 0.0 249
A001 2009-09-12 00:33 1.1 192
A001 2009-09-12 00:35 1.6 192
A001 2009-09-12 00:38 0.5 192
A001 2009-09-12 00:42 0.8 192

The results are:

Tagname DateTime Value QualityDetail


A001 2009-09-12 00:20 1.3 192
A001 2009-09-12 00:26 0.9 4288
A001 2009-09-12 00:28 NULL 249
A001 2009-09-12 00:35 1.6 4288

The sample data points and the res ults are mapped on the following chart. Only the data falling
between the time start and end marks at 00:20 and 00:40 (shown on the chart as dark vertical lines)
are returned by the query. The resolution is set at 10,000 milliseconds.

Version 17.0.18000 61
Wonderware Historian Retrieval Guide Data Retrieval Options

Because there is no value that matches the start time, an initial value at 00:20 is returned based on the
maximum value of the prec eding cycle, which is the data point at 00:15. In the two subsequent cycles,
the maximum values are at 00:26 and 00:35. The quality for thes e two values is set to 4288 (4096 +
192). The remaining data points are excluded becaus e they are not maximums. In addition, the first
NULL at 00: 28 is included, but the second NULL (at 00:29) is not.

Integral Retrieval
Integral retrieval calculates the values at retrieval cycle boundaries by integrating the graph described
by the points stored for the tag. Therefore, it works much like average retrieval, but it additionally
applies a scaling factor. This retrieval mode is useful for calculating volume for a particular tag. For
example, if one of your tags represents product flow in gallons per second, integral retrieval allows you
to retrieve the total product flow in gallons during a certain time period.
Integral retrieval is a true cyclic mode. It returns one row for each tag in the query for each cycle. The
number of cycles is based on the specified resolution or cyc le count.
Integral retrieval only works with analog tags. For all other tags, normal cyclic results are returned.

Integral Retrieval - How It Works

Calculating values for a cycle in integral retrieval is a two -step process:


 First, the historian calculates the area under the graph created by the dat a points. This works the
same as in average retrieval. For more information, see Average Retrieval on page 48.
 After this area has been found, it is scaled using the value of the IntegralDivisor column in the
EngineeringUnit table. This divisor expresses the conversion factor from the actual rate to one of
units per second.
For example, if the time-weighted average for a tag during a 1-minute cycle is 3.5 liters per second,
integral retrieval ret urns a value of 210 for that cycle (3.5 liters per second multiplied by 60 seconds).

Integral Retrieval - Supported Value Parameters

You can use various parameters to adjust which values are returned in integral retrieval mode. For
more information, see the following sections:
 Cycle Count (X Values over Equal Time Intervals) (wwCycleCount) on page 90
 Resolution (Values Spaced Every X ms) (wwResolution) on page 92
 History Version (wwVersion) on page 103
 Interpolation Type (wwInterpolationType) on page 104

62 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

 Timestamp Rule (wwTimestampRule) on page 106


 Qualit y Rule (wwQualit yRule) on page 111

Integral Retrieval - Query Example


To use the integral retrieval mode, set the following parameter in your query.

wwRetrievalMode = 'Integral'

In this example, the integral is computed for each of five 1 -minut e long cycles. The wwQualityRule
parameter is used to ensure that only points with good quality are used in the computation, which
means that points with doubt ful quality are discarded. The rules used to determine the returned
OPCQuality are the same as described for a time weighted average query.

SELECT DateTime, TagName, CONVERT(DECIMAL(10, 2), Value) AS Flow, OPCQuality,


PercentGood FROM History
WHERE TagName = 'FlowRate'
AND DateTime >= '2004-06-07 08:00'
AND DateTime < '2004-06-07 08:05'
AND wwRetrievalMode = 'Integral'
AND wwCycleCount = 5
AND wwQualityRule = 'Good'
The results are:

DateTime TagName Flow OPCQuality PercentGood


(interval 1) 2004-06-07 FlowRate 2862.97 192 100.0
08:00:00.000
(interval 2) 2004-06-07 FlowRate 9436.85 192 100.0
08:01:00.000
(interval 3) 2004-06-07 FlowRate 2480.24 192 100.0
08:02:00.000
(interval 4) 2004-06-07 FlowRate 7379.71 192 100.0
08:03:00.000
(interval 5) 2004-06-07 FlowRate 6317.32 192 100.0
08:04:00.000

Also, the "phantom" cycle affects the integral ret rieval mode just as it does the average retrieval mode.
For examples, see Querying Aggregate Data in Different Ways on page 168.

Integral Retrieval - Initial and Final Values

If wwTimeStampRule = END, the initial value is calculated by performing an integral calculation on the
cycle leading up to the query start time. No special handling is done for the final value.
If wwTimeStampRule = STA RT, the final value is calculated by performing an integral calculation on
the cycle following the query end time. No special handling is done for the initial value.

Integral Retrieval - Handling NULL Values

Version 17.0.18000 63
Wonderware Historian Retrieval Guide Data Retrieval Options

Gaps introduced by NULL values are not included in the integral calculations. The average only
considers the time ranges with good values. TimeGood indicates the total time per cycle that the tags
value was good.

Slope Retrieval

Slope retrieval returns the slope of a line drawn through a given point and the point immediately before
it, thus expressing the rate at which values change.
This retrieval mode is useful for detecting if a tag is changing at too great a rate. For example, you
might have a temperature that should steadily rise and fall by a small amo unt, and a sharp increase or
decrease could point to a potential problem.
The slope retrieval mode can be considered a delta mode. Apart from the initial value and a value at
the query end time, all returned points are calculated delta points returned with the timestamp of an
actual delta point.
Slope retrieval only works with analog tags. For all other tags, normal delta results are returned.
All returned values are in chronological order. If multiple points are to be ret urned for a particular
timestamp, they are returned in the order in which the tags were specified in the query.

Slope Retrieval - How It Works


The following illustration shows how the slope is calculated for an analog tag.

This example has a start time of TS and an end time of TE.


For the queried tag, a total of nine points are found, represented by the markers P 1 through P9. Of
these points, eight represent normal analog values. The point P 5 represents a NULL due to an I/O
Server disconnect, which causes a gap in the data between P 5 and P 6.
For every point in the time period, slope retrieval returns the slope of the line going through that point
and the point immediately before it. For two points P 1 and P 2 occurring at times T1 and T2, the slope
formula is as follows:
(P2 - P1) / (T2 - T1)
The difference between T1 and T2 is measured in seconds. Therefore, the returned value represents
the change in Engineering Units per second.
In this example, point P 2 is located at the query start time, and bec ause there is a prior value (P 1), the
slope of the line through both points is calculated and returned at time TS. Similarly, slopes are
calculated to be returned at times T3, T4, T7, and T8. The slope is also calculated for the line through P 8
and P9, but that value is returned as point P TE at the query end time.

64 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

For point P 6, there is no prior point with which to perform a slope calculation. Instead, the slope of the
flat line going through the point (that is, the value 0) is calculated. At the time of P 5, NULL is returned.
The quality detail and OPC quality returned wit h a slope point is always directly inherited from the point
that also provides the time stamp. In this example, this means that point P 2 provides the qualities for
the slope point returned at the query start time, TS.

Slope Retrieval - Supported Value Parameters

You can use various parameters to adjust which values are returned in slope retrieval mode. For more
information, see the following sections:
 History Version (wwVersion) on page 103
 Qualit y Rule (wwQualit yRule) on page 111

Slope Retrieval - Query Example


To use the slope retrieval mode, set the following parameter in your query.

wwRetrievalMode = 'Slope'

For example, the following query calculates and returns the rate of change of the ReactTemp tag in
°C/second. The initial value in the Quality column at the query start time shows no value is located
exactly at that time, so the slope returned is the same as the one ret urned at the next delta point. (For
more information on initial values, see Determining Cycle Boundaries on page 139.)
At 08:01:17.947 the tag has two delta points, so a slope is calculated and retu rned for the first point,
while a NULL is returned at the second one with a special QualityDetail of 17, indicating that no slope
can be calculated as it is either plus or minus infinite.

SELECT DateTime, TagName, CONVERT(DECIMAL(10, 4), Value) AS Slope, Quality,


QualityDetail FROM History
WHERE TagName = 'ReactTemp'
AND DateTime >= '2005-04-17 08:00'
AND DateTime <= '2005-04-17 08:05'
AND wwRetrievalMode = 'Slope'
The results are:

DateTime TagName Slope Quality QualityDetail

2005-04-17 08:00:00.000 ReactTemp 3.8110 133 192


2005-04-17 08:00:00.510 ReactTemp 3.8110 0 192
2005-04-17 08:00:01.713 ReactTemp 4.1563 0 192
2005-04-17 08:00:02.917 ReactTemp 4.1563 0 192
2005-04-17 08:00:04.230 ReactTemp 3.8081 0 192
2005-04-17 08:00:05.433 ReactTemp 4.1563 0 192
… … …

2005-04-17 08:01:16.743 ReactTemp -1.7517 0 192


2005-04-17 08:01:17.947 ReactTemp -27.0158 0 192
2005-04-17 08:01:17.947 ReactTemp NULL 1 17

Version 17.0.18000 65
Wonderware Historian Retrieval Guide Data Retrieval Options

DateTime TagName Slope Quality QualityDetail

2005-04-17 08:01:19.260 ReactTemp -1.7530 0 192


2005-04-17 08:01:20.463 ReactTemp -1.9119 0 192
2005-04-17 08:01:21.667 ReactTemp -1.9119 0 192
2005-04-17 08:01:22.977 ReactTemp -1.7517 0 192
… … …

Slope Retrieval - Initial and Final Values

An initial value is always generated. If a point is stored exactly at the query start time, the slope is
returned as the slope between that point and the previous point. Otherwise, the slope is calculated
using the slope of the points before and aft er the query start time.
A final value is always generated. If a point is stored exactly at the query end time, the slope is
returned as the slope between that point and the previous point. Otherwise, the slope is calculated
using the slope of the points before and aft er the query end time.

Slope Retrieval - Handling NULL Values

The first NULL following a non-NULL value is returned. Subsequent NULL values are not. If a point is
preceded by a NULL, the slope for that point will be zero.

Counter Retrieval
Counter retrieval allows you to accurately retrieve the delta change of a tag’s value over a period of
time even for tags that are reset upon reaching a "rollover value." The rollover value is defined in the
Wonderware Historian for each tag.
This retrieval mode is useful for determining how much of an item was produced during a particular
time period. For example, you might have an integer counter that keeps track of how many cartons
were produced. The counter has an indicator like this:

The next value after the highest value that can be physically shown by the counter is called the rollover
value. In this example, the rollover value is 10,000. When the counter reac hes the 9,999th value, the
counter rolls back to 0. Therefore, a counter value of 9,900 at one time and a value of 100 at a later
time means that you have produced 200 units during that period, even though the counter value has
dropped by 9,800 (9, 900 minus 100). Counter retrieval allows you to handle this situation and receive
the correct value. For each cycle, the counter ret rieval mode shows the increase in that counter during
the cycle, including rollovers.

Note: If Historian receives a data tag value that is outside of the specified engineering unit boundaries,
Historian ignores the received value and instead returns a 0. For example, if a value can be an integer
between 1 and 8, and the received value is 9, Historian returns 0 as the value for that tag during that
cycle.

66 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

Counter retrieval also works with floating point counters, whic h is useful for flow meter data. Similar to
the carton counter, some flow meters "roll over" after a certain amount of flow accumulates. For both
examples, the need is to convert the accumulating measure to a "delt a change" value over a given
period.
Counter retrieval is a true cyclic mode. It returns one row for each tag in the query for each cycle. The
number of cycles is based on the specified resolution or cycle count.
The counter algorithm is only applied to analog tags and to discrete tags. For integer analog tags, the
result will be an integer returned as a float data type. For a real analog tag, the rollover value and the
result may be real values and can include fractional values. If a query contains tags of other types,
then no rows are returned for those tags. For discrete tags, the rollover value is assumed to be 2.
The rules used to determine the OP CQuality returned with a counter value are the same as for a time
weighted average query. For more information, see Qualit y Rule (wwQualityRule) on page 111. When
a rollover has occurred in the calculation cycle, a special quality detail of 212 is returned in all
non-NULL cases.
CTU counters will default to "signed integer" tags when imported into the Historian, giving a normal
range of -2147483648 to 2147483647 (for a 32-bit integer). In operation, these count ers will count up
to the upper limit and "rollover" to the lower limit on the next increment. If these tags are changed to be
"unsigned integers" the normal range will be 0 to 4294967295 and values will rollover to "0",
conforming to the expected behavior of a tag used with "count er" retrieval. When used with a 16-bit
CTU counter, the same rules apply, but the range of values is -32768 to 32767 as "signed" and 0 to
65535 for an "unsigned".

Counter Retrieval - How It Works

The following illustration shows how the counter algorithm determines the count for an analog tag.

This example has a start time of TC0 and an end time of TC3. The resolution has been set in such a way
that the historian returns dat a for three complete cycles starting at TC0, TC1, and TC2, and an incomplete
cycle starting at TC3.
For the queried tag, a total of twelve points are found throughout the cycles represented by the
markers P 1 through P 12. Of these points, eleven represent normal analog values. The point P 9
represents a NULL due to an I/O Server disconnect, which causes a gap in the data bet ween P 9 and
P10. Point P 12 is not considered because it is outside of the query time frame.
All points are considered in the counter calculation, but only the yellow ones are actually used to
determine which values to return to the client. The returned points are P C0, PC1, PC2 and PC3, shown in
green at the top to indicate that there is no simple relationship between them and any of the actual
points.

Version 17.0.18000 67
Wonderware Historian Retrieval Guide Data Retrieval Options

All cycle values are calculat ed as the delta change between the cycle time in question and the previous
cycle time, taking into account the number of rollovers between the t wo points in time. The counter
algorithm assumes that a rollover occurred if the current value is lower than the previous value. The
initial value at the query start time (P C1) is calculated the same way, only based on a phant om cycle
before the query start time.
For example, the formula to calculate P C1 is as follows:
PC1 = n * VR + P6 - P1
where:
 n = the number of rollovers that have occurred during the cycle
 VR = the rollover value for the tag
If either n or VR are equal to zero, P C1 is simply the difference bet ween the values P 1 and P6.
In the case of cycle C2, there is no value at the cycle time, so the NULL value represented by point P 9
is returned. In the case of cycle C3, a NULL is again returned, because there is no counter value at the
previous cycle boundary to use in the calculation. There must be a full cycle of values in order for the
counter to be calculated.
If a gap is fully contained inside a cycle, and if points occur within the cycle on both sides of the gap,
then a counter value is returned, even though it may occasionally be erroneous. Zero or one rollovers
are assumed, even though the counter might have rolled over multiple times.

Counter Retrieval - Calculations for a Manually Reset Counter

If you have a counter that you typically reset manually before it rolls over, you must set the rollover
value for the tag to 0 so that the count is simply how much change occurred since the manual reset.
For example, assume that you have the following dat a values for five consecutive cycle boundaries,
and that the value 0 occurs as the first value within the last cycle:
100, 110, 117, 123, 3
If you set the rollover value to 0, the counter retrieval mode assumes that the 0 following the value 123
represents a manual reset, and returns a value of 3 for the last cycle, which is assumed to be the count
after the manual reset. The value 0 itself does not contribute 1 to the counter value in this case.
If the rollover value is instead set to 200, then the counter ret rieval mode assumes that the value 0
represents a normal rollover, and a count of 80 is calculated and returned (200 - 123 + 3). In this case,
the value 0 cont ribut es 1 to the counter value, and that is the change from the value 199 to the value
200.

Counter Retrieval - Using a Counter Deadband

You can set a deadband for counter retrieval to better handle reporting of rat es and quantities. For
example, setting a counter deadband can help to:
 Distinguish between counter resets and rollo vers.
 Filter out counter reversals.
The counter deadband is the percentage of the full range of the counter.
For example, if you set the counter deadband to be 10, then any counter reset that occurs within the
top 10% of the range is assumed to be a rollover and is counted as such.

68 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

For a reversal, you might have a conveyor belt carrying boxes that are counted as they pass by a
station. If a jam occurs, you might reverse the convey or belt to clear it, resulting in the counter
decrementing and then incrementing again. In this case, a counter deadband of 10 would discard any
duplicate counts within 10% of the range starting from the point of reversal. Only one reversal can be
detected until the rollover occurs.

Counter Retrieval - Supported Value Parameters

You can use various parameters to adjust which values are returned in integral retrieval mode. For
more information, see the following sections:
 Cycle Count (X Values over Equal Time Intervals) (wwCycleCount) on page 90
 Resolution (Values Spaced Every X ms) (wwResolution) on page 92
 History Version (wwVersion) on page 103
 Timestamp Rule (wwTimestampRule) on page 106
 Qualit y Rule (wwQualit yRule) on page 111

Counter Retrieval - Initial and Final Values

An initial value is returned using the period leading up to the query start time.
A data point that has a cycle time is used to generate the counter value for its preceding cycle. A NULL
point with cycle time will cause the preceding cycle to end in a gap and the following cycle to start with
a gap.

Counter Retrieval - Handling NULL Values

If wwQualityRule is configured as OP TIMIS TIC, NULL data points will not be used in calculation. 0.0
will be used as the starting base value for the query unless the query data starts with a NULL. If the
query starts with a NULL, the value change for the cycle is calculated from the first actual value in the
cycle, rather than 0.
Otherwise, if any points considered in a cycle have UNCE RTAIN quality, the result for that row will also
have UNCERTA IN quality. Any cycle that starts or ends in a gap will have a quality detail of 65536.
The quality detail of DOUB TFUL will be used with the counter result for the cycles, if a NULL point is
considered for the cycle and the counter result is not NULL.

Counter Retrieval - Handling Illegal Values

If the configured rollover value is larger than 0.0, then the data points whose values are greater than or
equal to the rollover value causes the counter value for the cycle to be set to 0.0, with
qdIO_FILTERE DPOINT applied to the quality detail.
Similarly, if any data point with a value less than 0.0 is found in a cycle, the counter value for the cycle
is set to 0.0, with qdIO_FILTERE DPOINT applied to the quality detail.

Counter Retrieval - Query Example


To use the counter mode, set the following parameter in your query.

Version 17.0.18000 69
Wonderware Historian Retrieval Guide Data Retrieval Options

wwRetrievalMode = 'Counter'
In the following example, the rollover value for the SysTimeS ec system tag is set to 0. In a two-minute
time span, the SysTimeS ec tag increments from 0 to 59 two times. The following query returns the total
count within the two-minute time span, which begins with Start Time and ends with Dat eTime. The
QualityDetail of 212 indicates that a count er rollover occurred during the query time range.

select StartDateTime, DateTime, TagName, Value, Quality, QualityDetail as QD


from History
where TagName = 'systimesec'
and DateTime > '2015-08-13 1:00'
and DateTime <= '2015-08-13 1:02'
and wwRetrievalMode = 'counter'
and wwCycleCount = 1
The results are:

StartTime DateTime TagName Value Quality QD


2015-08-13 2015-08-13 SysTimeSec 120 0 212
01:00:00.0000000 01:02:00.0000000

ValueState Retrieval
ValueState retrieval returns information on how long a tag has been in a particular value state during
each ret rieval cycle. That is, a time-in-state calculation is applied to the tag value.
This retrieval mode is useful for determining how long a machine has been running or stopped, how
much time a process spent in a particular state, how long a valve has been open or closed, and so on.
For example, you might have a steam valve that releases steam into a reactor, and you want to know
the average amount of time the valve was in the open position during the last hour. ValueState ret rieval
can return the shortest, longest, average, or total time a tag spent in a state, or the time spent in a
state as a percentage of the total cycle length.
When you use ValueState retrieval for a tag in a trend chart, you must specify a single value state for
which to retrieve information. ValueState retrieval then returns one value for each cycle—for example,
the total amount of time that the valve was in the "open" state during each 1-hour cycle. This
information is suitable for trend display.
If you don’t specify a state, ValueState ret rieval returns one row of information for each value that the
tag was in during each cycle. For example, this would ret urn not only the time a valve was in the
"open" state, but also the time it was in the "closed" state. This information is not suitable for
meaningful display in a regular trend. You can, however, retrieve this type of information in a query and
view it as a table.
ValueState retrieval works with integer, discrete, string, and state summary tags. For other types of
tags, no rows are returned. NULL values are treated like any other distinct state.
The values returned at the query start time are the result of applying the algorithm to a "phantom" cycle
preceding the query range. It is assumed that the tag value at the start of the cycle is located at that
point in time.
To specify the type of calculation, set the wwStateCalc parameter in the query. For more information,
see State Calculation (wwSt ateCalc) on page 118.

70 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

ValueState Retrieval - How It Works


The following illustration shows how ValueState retrieval returns values for a discrete tag.

Value
ValueState Retrieval

C0 C1 C2 C3
PC0 PC1 PC2 PC3
ON

OFF Gap

1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 21 22 23 24 25 26 27 28 29
Time
TC0 TC1 TC2 TC3

This example has a start time of TC0 and an end time of TC3. The resolution has been set in such a way
that the historian returns dat a for three complete cycles starting at TC0, TC1, and TC2, and an incomplete
cycle starting at TC3. Time is measured seconds.
A gap in the data occurs in the third cycle due to an I/O Server disconnect.
The state calculation is based on each cycle, and the values returned at the query start time are not
regular initial values, but are the resulting values that occur after applying the algorithm to the last cycle
preceding the query range. The returned points are P C0, PC1, PC2 and PC3, shown in green at the top to
indicate that there is no simple relationship between the calculated values and any of the actual points.
Assume the query is set so that the total time (wwStateCalc = ‘Total’)in the two states are returned.
The timestamping is set to use the cycle end time.
 For TC0, the query returns two rows (one for the "on" state and one for the "off" state), calculated as
a result of the "phantom" cycle that precedes the query start time. The values have a ti mestamp of
the query start time.
 For TC1, one row is returned for the "on" state. The "on" state occurred twice during the cycle--one
time for four seconds and again for two seconds before the cycle boundary, and the total time
returned is six seconds. The state was "off" twice during the cycle for a total time of four seconds,
and one row is returned wit h that value.
 For TC2, one row is returned for the "on" state, and one row is returned for the "off" state. The "on"
state occurred for a total of nine seconds between the cycle boundaries, and the "off" state
occurred for a total of one second.
 For TC3, one row is returned for the "on" state, and one row is returned for the "off" state. The "on"
state occurred for a total of four seconds bet ween the cycle boundaries, and the "off" state
occurred for a total of three seconds. An additional row is returned for the NULL state occurring as
a result of the I/O Server disconnect.
Using the same data, if you queried the total contained time for the states, the foll owing is returned:
 For TC0, the query returns two values (one for the "on" state and one for the "off" state), calculated
as a result of the "phantom" cycle the precedes the query start time. The value has a timestamp of
the query start time.
 For TC1, one row is returned for the "on" state, and one row is returned for the "off" state. The "on"
state occurred one time for four seconds within the cycle. The two seconds of "on" time that
crosses the cycle boundary does not contribute to the total time. The st ate was "off" one time
during the cycle for two seconds completely within the cycle boundary.

Version 17.0.18000 71
Wonderware Historian Retrieval Guide Data Retrieval Options

 For TC2, the state was not "on" for any contained time between the cycle. Both occurrences of the
"on" state cross over a cycle boundary, so no rows are returned for this state. One row is returned
for the "off" state. The state was "off" one time during the cycle for one seconds completely within
the cycle boundary.
 For TC3, one row is returned for the "on" state, and one row is returned for the "off" state. The state
was "on" for a single contained time of two seconds bet ween the cycle boundaries. The state was
"off" three times during the cycle for three seconds completely within the cycle boundary. An
additional row is returned for the NULL state occurring as a result of the I/O Server disconnect. The
state was NULL for a total of three seconds. The I/O Server disconnect that "disrupted" the off
state is treated as its own state, thereby changing what would have been a single "off" state
instance of five seconds into two instances of the "off" state for one second each.

ValueState Retrieval - Supported Value Parameters

You can use various parameters to adjust which values are returned in ValueState retrieval mode. For
more information, see the following sections:
 Cycle Count (X Values over Equal Time Intervals) (wwCycleCount) on page 90
 Resolution (Values Spaced Every X ms) (wwResolution) on page 92
 History Version (wwVersion) on page 103
 Timestamp Rule (wwTimestampRule) on page 106
 Qualit y Rule (wwQualit yRule) on page 111
 State Calculation (wwStateCalc ) on page 118

ValueState Retrieval - Query Examples

To use theValueState retrieval mode, set the followin g parameter in your query.

wwRetrievalMode = 'ValueState'
To specify the type of aggregation, set the wwStat eCalc parameter in the query, such as:

wwStateCalc = 'Total'
Be sure that you use the "<=" operator for ending date/time.
For examples, see the following:
 ValueState Retrieval Query 1: Minimum Time in State on page 72
 ValueState Retrieval Query 2: Minimum Time in State for a Single Tag on page 73
 ValueState Retrieval Query 3 on page 73
 ValueState Retrieval Query 4 on page 74
 ValueState Retrieval Query 5 on page 74
 ValueState Retrieval Query 6: Querying State Summary Values on page 75

ValueState Retrieval Query 1: Minimum Time in State


The following query finds the minimum time-in-state for the SteamV alve discrete tag. Note that
minimum times are returned for each state for bot h the five -minute phantom cycle before the query
start time and for the single ret rieval cycle between 10:00 and 10:05.

72 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

SELECT DateTime, TagName, vValue, StateTime, wwStateCalc FROM History


WHERE TagName IN ('SteamValve')
AND DateTime >= '2005-04-17 10:00:00'
AND DateTime <= '2005-04-17 10:05:00'
AND wwCycleCount = 1
AND wwRetrievalMode = 'ValueState'
AND wwStateCalc = 'Min'
The results are:

DateTime TagName vValue StateTime wwStateCalc


2005-04-17 10:00:00.000 SteamValve 0 35359.0 MINIMUM
2005-04-17 10:00:00.000 SteamValve 1 43749.0 MINIMUM
2005-04-17 10:05:00.000 SteamValve 0 37887.0 MINIMUM
2005-04-17 10:05:00.000 SteamValve 1 43749.0 MINIMUM

ValueState Retrieval Query 2: Minimum Time in State for a Single Tag


The following query finds the minimum time-in-state for the SteamV alve discrete tag for the "on" state.
Note that minimum times are returned for each state for both the five -minut e phantom cycle before the
query start time and for the single retrieval cycle between 10:00 and 10:05.

SELECT DateTime, TagName, vValue, StateTime, wwStateCalc FROM History


WHERE TagName IN ('SteamValve')
AND DateTime >= '2005-04-17 10:00:00'
AND DateTime <= '2005-04-17 10:05:00'
AND wwCycleCount = 1
AND wwRetrievalMode = 'ValueState'
AND wwStateCalc = 'Min'
AND State = '1'
The results are:

DateTime TagName vValue StateTime wwStateCalc


2005-04-17 10:00:00.000 SteamValve 1 43749.0 MINIMUM
2005-04-17 10:05:00.000 SteamValve 1 43749.0 MINIMUM

ValueState Retrieval Query 3


The following query finds the maximum time -in-state for the SteamV alve discrete tag in the same time
period as in Query 1. Note how bot h the minimum and maximum values for the "1" state are very
similar, while they are very different for the "0" state. This is due to the "cut-off" effect.

SELECT DateTime, TagName, vValue, StateTime, wwStateCalc FROM History


WHERE TagName IN ('SteamValve')
AND DateTime >= '2005-04-17 10:00:00'
AND DateTime <= '2005-04-17 10:05:00'
AND wwCycleCount = 1
AND wwRetrievalMode = 'ValueState'
AND wwStateCalc = 'Max'
The results are:

Version 17.0.18000 73
Wonderware Historian Retrieval Guide Data Retrieval Options

DateTime TagName vValue StateTime wwStateCalc


2005-04-17 10:00:00.000 SteamValve 0 107514.0 MAXIMUM
2005-04-17 10:00:00.000 SteamValve 1 43750.0 MAXIMUM
2005-04-17 10:05:00.000 SteamValve 0 107514.0 MAXIMUM
2005-04-17 10:05:00.000 SteamValve 1 43750.0 MAXIMUM

ValueState Retrieval Query 4


The following query returns the total of time in state for a discrete tag. In this example, the
TimeStampRule system parameter is set to "End" (the default setting), so the returned values are
timestamped at the end of the cycle. The returned rows represent the time-in-state behavior during the
period starting at 2005-04-13 00:00: 00.000 and ending at 2005-04-14 00:00: 00.000.

SELECT DateTime, vValue, StateTime, wwStateCalc FROM History


WHERE DateTime > '2005-04-13 00:00:00.000'
AND DateTime <= '2005-04-14 00:00:00.000'
AND TagName IN ('PumpStatus')
AND wwRetrievalMode = 'ValueState'
AND wwStateCalc = 'Total'
AND wwCycleCount = 1
The results are:

DateTime vValue StateTime wwStateCalc


2005-04-14 00:00:00 NULL 1041674.0 TOTAL
2005-04-14 00:00:00 On 56337454.0 TOTAL
2005-04-14 00:00:00 Off 29020872.0 TOTAL

ValueState Retrieval Query 5


The following query returns the percentage of time in state for a discrete tag for multiple retrieval
cycles. The TimeStampRule system parameter is set to "End" (the default setting), so the returned
values are timestamped at the end of the cycle. Note that the first row returned represents the results
for the period starting at 2003-07-03 22: 00:00. 000 and ending at 2003-07-04 00: 00:00.000.
The "Percent" time-in-state retrieval mode is the only mode in which the StateTime column does not
return time data. Instead, it returns percent age data (in the range of 0 to 100 percent) representing the
percentage of time in state.

SELECT DateTime, vValue, StateTime, wwStateCalc FROM History


WHERE DateTime >= '2003-07-04 00:00:00.000'
AND DateTime <= '2003-07-05 00:00:00.000'
AND TagName IN ('PumpStatus')
AND Value = 1
AND wwRetrievalMode = 'ValueState'
AND wwStateCalc = 'Percent'
AND wwCycleCount = 13
The results are:

DateTime vValue StateTime wwStateCalc

74 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

DateTime vValue StateTime wwStateCalc


2003-07-04 00:00:00 1 50.885 PERCENT
2003-07-04 02:00:00 1 82.656 PERCENT
2003-07-04 04:00:00 1 7.082 PERCENT
2003-07-04 06:00:00 1 7.157 PERCENT
2003-07-04 08:00:00 1 55.580 PERCENT
2003-07-04 10:00:00 1 28.047 PERCENT
2003-07-04 12:00:00 1 47.562 PERCENT
2003-07-04 14:00:00 1 74.477 PERCENT
2003-07-04 16:00:00 1 40.450 PERCENT
2003-07-04 18:00:00 1 78.313 PERCENT
2003-07-04 20:00:00 1 54.886 PERCENT
2003-07-04 22:00:00 1 39.569 PERCENT
2003-07-05 00:00:00 1 50.072 PERCENT

ValueState Retrieval Query 6: Querying State Summary Values


If state summary values are queried and the cycle boundaries match the summary periods, the
ValueState calculations are supported and return valid results.
If state summary points are queried and the cycle boundaries do not match the summary periods, the
ValueState calculations are supported, but they return DOUB TFUL (QualityDet ail = 64) results.
State summaries are included in the cycle where the summary end time occurs. This causes results
that do not match queries against the source tag and may cause inaccurate res ults, such as a total
state time that is greater than the cycle time.
For example, this can occur if SysTimeSec is summarized with a state summary with one minute
resolution, but then queried with 10 second int ervals. In most of the retrieval cycles, there will be no
values, but in the cycle that includes the summary end time (one in six of the ret rieval cycles), all 60
states would be returned wit h each state having a state time of 1 second for a total of 60 seconds of
state time in a 10 second retrieval cycle.

ValueState Retrieval - Initial and Final Values

The values returned at the query start time are the result of applying the algorithm to the last cycle
preceding the query range.

ValueState Retrieval - Handling NULL Values

NULLs are considered a state and are reported along with the other states.

Version 17.0.18000 75
Wonderware Historian Retrieval Guide Data Retrieval Options

RoundTrip Retrieval
RoundTrip retrieval is very similar to ValueState retrieval in that it performs calculations on state
occurrences in the within a cycle period you specify. However, ValueState retrieval uses the time spent
in a certain state for the calculation, and RoundTrip ret rieval uses the time between consec utive
leading edges of the same state for its calculations.
You can use the RoundTrip retrieval mode for increasing the efficiency of a process. For example, if a
process produces one item per cycle, then you would want to minimize the time lapse between two
consecutive cycles.
The RoundTrip mode returns a rows for each state in any given cycle. RoundTrip retrieval only works
with integer analog tags, discrete tags, and string tags. If real analog tags are specified in the query,
then no rows are returned for these tags. RoundTrip retrieval is not applied to state s ummary or analog
summary tags. NULL values are treated as any other distinct value and are used to analyze the round
trip for disturbances.
RoundTrip retrieval is supported for the History and StateWideHistory tables.
Any point on the boundary of the end cycle will be considered to the next cycle. The point on the
boundary of the end query range is not counted in the calculation except that it is used to indicate that
the previous state is a contained state.
If no roundtrip state is found within the cycle for a support ed tag, a NULL StateTime value is returned.
If there is no valid point prior to the phantom cycle, a NULL state is returned for the phantom cycle.

RoundTrip Retrieval - How It Works

The following illustration shows how RoundTrip retrieval returns values for a discret e tag.

Value
RoundTrip Retrieval

C0 C1 C2 C3
PC0 Round-trip PC1 PC2 PC3
ON

OFF Gap

Round-trip

1 2 3 4 5 6 7 8 9 11 12 13 14 15 16 17 18 19 21 22 23 24 25 26 27 28 29
Time
TC0 TC1 TC2 TC3

This example has a start time of TC0 and an end time of TC3. The resolution has been set in such a way
that the historian returns dat a for three complete cycles starting at TC0, TC1, and TC2, and an incomplete
cycle starting at TC3. Time is measured seconds.
A gap in the data occurs in the third cycle due to an I/O Server disconnect.
The state calculation is based on each cycle, and the values returned at the query start time are not
regular initial values, but are the resulting values that occur after applying the algorithm to the last cycle
preceding the query range. The returned points are P C0, PC1, PC2 and PC3, shown in green at the top to
indicate that there is no simple relationship between the calculated values and any of the actual points.
Assume the query is set so that the total contained time in the two states are ret urned. The
timestamping is set to use the cycle end time. The RoundTrip ret rieval mode returns values for states
that are completely contained within the cycle boundaries. The following is returned:

76 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

 For TC0, the query returns two values (one for the "on" state and one for the "off" state), calculated
as a result of the "phantom" cycle that preceeds the query start time. The value has a timestamp of
the query start time.
 For TC1, one row is returned for the "on" state, and one row is returned for the "off" state. The
round-trip for the "on" state occurred one time for four seconds completely within the cycle
boundary. The round-trip for the "off" state occurred one time during the cycle for five seconds.
 For TC2, a round-trip did not occur for either state within the cycle boundaries. One NULL row is
returned for this cycle.
 For TC3, one row is returned for the "on" state, and one row is returned for the "off" state. The state
was "on" for a single contained time of two seconds bet ween the cycle boundaries. The state was
"off" one time during the cycle for one second completely within the cycle boundary. An additional
row is ret urned for the NULL state occurring as a result of the I/O Server disconnect.
 For TC3, one row is returned for the "on" state, and one row is returned for the "off" state. The state
was "on" for a single contained time of three seconds between the cycle boundaries. One row is
returned for the "off" state for a total cont ained time of seven seconds. (The first round-t rip for the
"off" state includes the I/O Server disconnect for a length of four seconds. The second round -trip
has a length of three seconds.) An additional row is returned for the NULL state occurring as a
result of the I/O Server disconnect, and the returned value is NULL because there is no round-trip
during the cycle for it. The I/O Server disconnect that "disrupted" the off state is treated as its own
state, thereby changing what would have been a single "off" state instance of five seconds into two
instances of the "off" state for one second each.

RoundTrip Retrieval - Supported Value Parameters

You can use various parameters to adjust the values that must be ret urned in the RoundTrip retrieval
mode. For more information, see the following sections:
 Timestamp Rule (wwTimestampRule) on page 106
 Qualit y Rule (wwQualit yRule) on page 111
 State Calculation (wwStateCalc ) on page 118

RoundTrip Retrieval - Query Examples


To use the RoundTrip retrieval mode, set the following parameter in your query:

wwRetrievalMode = ‘RoundTrip’
The following queries compare the res ults between ValueState retrieval and RoundTrip retrieval.
This first ValueState retrieval query returns the average amount of time that the 'Reactor1OutletValve'
tag is in "on" state and the average amount of time it is in the "off" state for a single cycle. Any state
changes that occur across the cycle boundaries are not included.

SELECT DateTime, vValue, StateTime


FROM History
WHERE TagName IN ('Reactor1OutletValve')
AND DateTime >= '2009-09-16 12:35:00'
AND DateTime <= '2009-09-16 12:55:00'
AND wwRetrievalMode = 'ValueState'
AND wwStateCalc = 'AvgContained'
AND wwCycleCount = 1
The results are:

Version 17.0.18000 77
Wonderware Historian Retrieval Guide Data Retrieval Options

DateTime vValue StateTime


2009-09-16 12:35:00.0000000 0 215878
2009-09-16 12:35:00.0000000 1 61729
2009-09-16 12:55:00.0000000 1 62827.5
2009-09-16 12:55:00.0000000 0 212856

The first two rows are for the "phantom" cycle leading up to the query start time and have a timestamp
of the query start time.
The second two rows show the average amount of time for each state and have a timestamp of the
query end time (t he default).
Compare these results to same basic query that instead uses RoundTrip ret rieval:

SELECT DateTime, vValue, StateTime


FROM History
WHERE TagName IN ('Reactor1OutletValve')
AND DateTime >= '2009-09-16 12:35:00'
AND DateTime <= '2009-09-16 12:55:00'
AND wwRetrievalMode = 'RoundTrip'
AND wwStateCalc = 'AvgContained'
AND wwCycleCount = 1
The results are:

DateTime vValue StateTime


2009-09-16 12:35:00.0000000 1 277607
2009-09-16 12:35:00.0000000 0 278580
2009-09-16 12:55:00.0000000 0 275683.5
2009-09-16 12:55:00.0000000 1 273845

RoundTrip Retrieval - Initial and Final Values

The values returned at the query start time are the result of applying the algorithm to the last cycle
preceding the query range.

RoundTrip Retrieval - Handling NULL Values

Like in the ValueState retrieval mode, the NULL state is treated as a valid distinct value. This allows
you to analyze round trips for disturbances.

Edge Detection for Events (wwEdgeDetection)


For Wonderware Historian, an event is the moment at which a detection criterion is met on historical
tag values in the Wonderware Historian. At a basic level, anything that can be determined by looking at
stored data can be used as an event.

78 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

When det ecting events, it is useful to pinpoint rows in a result set where the satisfaction of criteria in a
WHERE clause changed from true to false, or vice versa. For example, you may want to know when
the level of a tank went above 5 feet. The WHERE clause in a query for this example might be
TA NKLEVEL > 5. As the tank level approaches 5 feet, the criterion does not return true. Only when the
level crosses the line from not satisfying the criterion to satisfying it, does the event actually occur. This
imaginary "line" where the change occurs is called the edge.
Over a period of time, there may be many instanc es where the criteria cross the "edge" from being
satisfied to not satisfied, and vice-versa. The values on either side of this "edge" can be detected if you
configure your event tag to include this information. There are four possible options for edge detection:
none, leading, trailing, or both. You will get differing results based on which option you use:

Option Results

None Returns all rows that successfully meet the criteria; no edge detection is implemented
at the specified resolution.

Leading Returns only rows that are the first to successfully meet the criteria (return true) after
a row did not successfully meet the criteria (returned false).

Trailing Returns only rows that are the first to fail the criteria (return false) after a row
successfully met the criteria (returned true).

Both All rows satisfying both the leading and trailing conditions are returned.

Edge detection only applies to analog and discrete value detectors. Also, edge detection is handled
slightly differently based on whether you are using analog tags or discret e tags.
You can also use the ToDiscrete() query filter to determine when data values cross a particular
threshold. For more information, see Converting Analog Values to Discrete Values (ToDiscret e) on
page 121.
For more information on event detection with the Classic Event subsystem, see Classic Event
Subsystem in the Wonderware Historian Supplemental Guide.

Edge Detection for Analog Tags

For example, the behavior of the WHE RE clause as it processes a result set can be illustrated as:

D F
B
V
A
L
U
E

A C E G
TIME

Slopes A-B, C-D and E-F are rising edges, while slopes B-C, D-E and F-G are falling edges. The
slopes are affected by the WHERE clause, which is a combination of the wwEdgeDetection option and
the comparison operator used against the value.

Version 17.0.18000 79
Wonderware Historian Retrieval Guide Data Retrieval Options

The following table describes the rows that would be returned for the various edge detection settings:

Operator = < > <= >=

Leading Falling and Falling edge Rising edge Falling edge Rising edge
rising edges; only; first only; first only; first only; first
first value that value to meet value to meet value to meet value to meet
meets the the criteria.* the criteria. the criteria. * the criteria.
criteria.

Trailing Falling and Rising edge Falling edge Rising edge Falling edge
rising edges; only; equal to only; first only; first only; first
first value to the first value value to fail value to fail value to fail
fail the criteria to fail the the criteria.* the criteria. the criteria.*
after a value criteria.
meets the
criteria.

* If the falling edge is a vertical edge with no slope, the query will return the lowest value of that edge.
The following query selects all values of "SysTimeS ec" that are great er than or equal to 50 from the
History table between 10:00 and 10:02 a.m. on December 2, 2001. No edge det ection is specified.

SELECT DateTime, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND DateTime >= '2001-12-02 10:00:00'
AND DateTime <= '2001-12-02 10:02:00'
AND wwRetrievalMode = 'Cyclic'
AND wwResolution = 2000
AND Value >= 50
AND wwEdgeDetection = 'None'
The results are:

DateTime Value
2001-12-02 10:00:50.000 50
2001-12-02 10:00:52.000 52
2001-12-02 10:00:54.000 54
2001-12-02 10:00:56.000 56
2001-12-02 10:00:58.000 58
2001-12-02 10:01:50.000 50
2001-12-02 10:01:52.000 52
2001-12-02 10:01:54.000 54
2001-12-02 10:01:56.000 56

80 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

2001-12-02 10:01:58.000 58

Leading Edge Detection for Analog Tags

If Leading is specified as the parameter in the edge detection time domain extension, the only rows in
the result set are those that are the first to successfully meet the WHERE clause criteria (returned true)
after a row did not successfully meet the WHERE clause criteria (ret urned false).
The following query selects the first values of "SysTimeSec" from the History table to meet the Value
criterion between 10:00 and 10:02 a.m. on December 2, 2001.

SELECT DateTime, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND DateTime >= '2001-12-02 10:00:00'
AND DateTime <= '2001-12-02 10:02:00'
AND wwRetrievalMode = 'Cyclic'
AND wwResolution = 2000
AND Value >= 50
AND wwEdgeDetection = 'Leading'
The query will return only the two values that were greater than or equal to 50 for the time period
specified:

DateTime Value
2001-12-02 10:00:50.000 50
2001-12-02 10:01:50.000 50

Compare these results with the same query using no edge detection, as shown in Edge Detection for
Analog Tags on page 79. Notice that even though the original query returned ten rows, the edge
detection only returns the first row recorded aft er the event criteria returned true.

Trailing Edge Detection for Analog Tags

If Trailing is specified as the parameter in the edge detection extension, the only rows in the result set
are those that are the first to fail the criteria in the WHERE claus e (returned false) after a row
successfully met the WHERE clause criteria (ret urn ed true).
The following query selects the first values of "SysTimeSec" from the History table to fail the Value
criterion between 10:00 and 10:02 a.m. on December 2, 2001.

SELECT DateTime, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND DateTime >= '2001-12-02 10:00:00'
AND DateTime <= '2001-12-02 10:02:00'
AND wwRetrievalMode = 'Cyclic'
AND wwResolution = 2000
AND Value >= 50
AND wwEdgeDetection = 'Trailing'

Version 17.0.18000 81
Wonderware Historian Retrieval Guide Data Retrieval Options

The query returns only the two values that were the first to fail the criteria in the WHE RE clause for the
time period specified:

DateTime Value
2001-12-02 10:01:00.000 0
2001-12-02 10:02:00.000 0

Compare these results with the same query using no edge detection, as shown in Edge Detection for
Analog Tags on page 79. Notice that even though the original query returned ten recorded rows for
each value, the edge det ection only ret urns the first row recorded after the event criteria ret urned false.

Both Leading and Trailing Edge Detection for Analog Tags

If Bot h is specified as the parameter in the edge detection extension, all rows satisfying both the
leading and trailing conditions are returned.
The following query selects values of "SysTimeS ec" from th e History table that meet bot h the Leading
and Trailing criteria between 10:00 and 10:02 a.m. on December 2, 2001.

SELECT DateTime, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND DateTime >= '2001-12-02 10:00:00'
AND DateTime <= '2001-12-02 10:02:00'
AND wwRetrievalMode = 'Cyclic'
AND wwResolution = 2000
AND Value >= 50
AND wwEdgeDetection = 'Both'
The results are:

DateTime Value
2001-12-02 10:00:50.000 50

2001-12-02 10:01:00.000 0
2001-12-02 10:01:50.000 50
2001-12-02 10:02:00.000 0

Compare these results with the same query using no edge detection, as shown in Edge Detection for
Analog Tags on page 79. Notice that value of the first row in the original query is returned in the result
set.

Edge Detection for Discrete Tags

Edge detection for discrete tags operat es diffe rently than for analog tags. For example, assume the
following discrete tags are stored.

82 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

Tag Description

SysPulse Transitions between 1 and 0 every minute.

MyPulse Transitions between 1 and 0 every 40 seconds.

A representation of the data stored in the system is as follows:

The following queries select values of "SysPulse" and "MyPulse" that have a value of 1 (On) from the
History and WideHistory tables between 12:59 and 1:04 a.m. on December 8, 2001. No edge detection
is specified.
This is a query of the History table:

SELECT DateTime, TagName, Value


FROM History
WHERE TagName IN ('SysPulse','MyPulse')
AND DateTime > '2001-12-08 00:59:00'
AND DateTime <= '2001-12-08 01:04:00'
AND wwRetrievalMode = 'Delta'
AND Value = 1
AND wwEdgeDetection = 'None'
The results are:

DateTime TagName Value


2001-12-08 00:01:00.000 SysPulse 1
2001-12-08 00:01:00.000 MyPulse 1
2001-12-08 00:02:20.000 MyPulse 1
2001-12-08 00:03:00.000 SysPulse 1
2001-12-08 00:03:40.000 MyPulse 1

The following is a query of the WideHistory table:

SELECT * FROM OpenQuery(INSQL, 'SELECT DateTime, SysPulse, MyPulse FROM


WideHistory
WHERE DateTime > "2001-12-08 00:59:00"
AND DateTime < "2001-12-08 01:05:00"

Version 17.0.18000 83
Wonderware Historian Retrieval Guide Data Retrieval Options

AND SysPulse = 1
AND MyPulse = 1
AND wwRetrievalMode = "Delta"
AND wwEdgeDetection = "None"
')
The results are:

DateTime SysPulse MyPulse


2001-12-08 00:01:00.000 1 1

Leading Edge Detection for Discrete Tags

If Leading is specified as the parameter in the edge detection time domain extension, the only rows in
the result set are those that are the first to successfully meet the WHERE clause criteria (returned true)
after a row did not successfully meet the WHERE clause criteria (ret urned false).
The following queries select values of "SysPulse" and "MyPulse" that have a value of 1 (On) from the
History and WideHistory tables between 12:59 and 1:04 a.m. on December 8, 2001.
This example queries the History table, if the WHE RE clause criteria specify to return only discrete
values equal to 1 (On), then applying a leading edge detection does not change the result set.

SELECT DateTime, TagName, Value


FROM History
WHERE TagName IN ('SysPulse','MyPulse')
AND DateTime > '2001-12-08 00:59:00'
AND DateTime <= '2001-12-08 01:04:00'
AND Value = 1
AND wwEdgeDetection = 'Leading'

The results are:

DateTime TagName Value


2001-12-08 00:01:00.000 SysPulse 1
2001-12-08 00:01:00.000 MyPulse 1
2001-12-08 00:02:20.000 MyPulse 1
2001-12-08 00:03:00.000 SysPulse 1
2001-12-08 00:03:40.000 MyPulse 1

This example queries the WideHistory table, applying a leading edge detection requires that the
condition only evaluate to true if both values are equal to 1 (On).

SELECT DateTime, SysPulse, MyPulse FROM OpenQuery(INSQL, 'SELECT DateTime,


SysPulse, MyPulse
FROM WideHistory
WHERE DateTime > "2001-12-08 00:59:00"
AND DateTime <= "2001-12-08 01:04:00"
AND SysPulse = 1

84 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

AND MyPulse = 1
AND wwEdgeDetection = "Leading"
')

The results are:

DateTime SysPulse MyPulse


2001-12-08 00:01:00.000 1 1
2001-12-08 00:03:40.000 1 1

Compare these results with the same query using no edge detection, as shown in Edge Detection for
Discrete Tags on page 82. If you look at the diagram, you might think that a row could be returned at
00:03: 00, but bec ause both tags change at exactly this instant, their values are not returned. In a
normal process, it is unlikely that two tags would change at exactly at the same instant.

Trailing Edge Detection for Discrete Tags

If Trailing is specified as the parameter in the edge detection ex tension, the only rows in the result set
are those that are the first to fail the criteria in the WHERE claus e (returned false) after a row
successfully met the WHERE clause criteria (ret urned true).
This example queries the History table. If the WHERE claus e criteria specifies ret urning only discrete
values equal to 1 (On), then applying a trailing edge detection is the same as reversing the WHERE
clause (as if Value = 0 was applied).

SELECT DateTime, TagName, Value


FROM History
WHERE TagName IN ('SysPulse','MyPulse')
AND DateTime > '2001-12-08 00:59:00'
AND DateTime <= '2001-12-08 01:04:00'
AND Value = 1
AND wwEdgeDetection = 'Trailing'

The results are:

DateTime TagName Value


2001-12-08 00:01:40.000 MyPulse 1
2001-12-08 00:02:00.000 SysPulse 1
2001-12-08 00:03:00.000 MyPulse 1

2001-12-08 00:04:00.000 SysPulse 1

This example queries the WideHistory table. It applies a trailing edge detection returns the boundaries
where the condition ceases to be true (one of the values is equal to 0).

SELECT DateTime, SysPulse, MyPulse FROM OpenQuery(INSQL, 'SELECT DateTime,


SysPulse, MyPulse
FROM WideHistory
WHERE DateTime > "2001-12-08 00:59:00"

Version 17.0.18000 85
Wonderware Historian Retrieval Guide Data Retrieval Options

AND DateTime <= "2001-12-08 01:04:00"


AND SysPulse = 1
AND MyPulse = 1
AND wwEdgeDetection = "Trailing"
')

The results are:

DateTime SysPulse MyPulse


2001-12-08 00:01:40.000 1 1
2001-12-08 00:04:00.000 1 1

Compare these results with the same query using no edge detection, as shown in Edge Detection for
Discrete Tags on page 82. If you look at the diagram, you might think that a row could be returned at
00:03: 00, but bec ause both tags change at exactly this instant, their values are not returned. In a
normal process, it is unlikely that two tags would change at exactly at the same instant.

Both Leading and Trailing Edge Detection for Discrete Tags

If Bot h is specified as the parameter in the edge detection extension, all rows satisfying both the
leading and trailing conditions are returned.
The following queries select values of "SysPulse" and "MyPulse" that meet an edge detection of Both
for a value criterion of 1 (On) from the History and WideHistory tables between 12:59 and 1:04 a.m. on
December 8, 2001.

SELECT DateTime, TagName, Value


FROM History
WHERE TagName IN ('SysPulse','MyPulse')
AND DateTime > '2001-12-08 00:59:00'
AND DateTime <= '2001-12-08 01:04:00'
AND Value = 1
AND wwEdgeDetection = 'Both'

The results are:

DateTime TagName Value


2001-12-08 00:01:00.000 SysPulse 1
2001-12-08 00:01:00.000 MyPulse 1
2001-12-08 00:01:40.000 MyPulse 1
2001-12-08 00:02:00.000 SysPulse 1
2001-12-08 00:02:20.000 MyPulse 1
2001-12-08 00:03:00.000 SysPulse 1
2001-12-08 00:03:00.000 MyPulse 1
2001-12-08 00:03:40.000 MyPulse 1

86 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

2001-12-08 00:04:00.000 SysPulse 1

SELECT DateTime, SysPulse, MyPulse FROM OpenQuery(INSQL, 'SELECT DateTime,


SysPulse, MyPulse
FROM WideHistory
WHERE DateTime > "2001-12-08 00:59:00"
AND DateTime <= "2001-12-08 01:04:00"
AND SysPulse = 1
AND MyPulse = 1
AND wwEdgeDetection = "Both"
')

The results are:

DateTime SysPulse MyPulse


2001-12-08 00:01:00.000 1 1
2001-12-08 00:01:40.000 1 1
2001-12-08 00:03:40.000 1 1
2001-12-08 00:04:00.000 1 1

Compare these results with the same query using no edge detection, as shown in the Edge Det ection
for Discrete Tags on page 82.

Predictive Filter
Wonderware Historian supports predictive retrieval. Beginning with Wonderware Historian 2014 R2
Patch 01, the historian can return predictive data based on a "simple linear regression" (SLR)
algorithm. More capabilities will be added in future releases.
With Wonderware Historian, you can create a query based on data you have stored to predict
additional values in a trend. Historian returns predictive data based on a "simple linear regression"
(SLR) algorithm.
For example, based on your currently stored values, you could use the predictive retrieval feature to
help predict if a certain production target will be met by the end of the shift. Or, if the Historian loses
communication with the data source, you could us e predictive retrieval to determine whether and when
a tank is likely to become empty.
You can predict:
 Values in bet ween other values.
 Values that extend beyond stored values.
For example, suppose you already captured data for a tag with timestamps up to 3 p.m. on a certain
day, but not for the rest of the shift, which ran until 5 p.m., because of a power cut. With predictive
retrieval, you can view the interpolated results based bet ween 3 p.m. and 5 p.m. These results are
based on the data you received through 3 p.m.
The following is an example of a query that retrieves stored values and reports both those values and
additional predictive dat a:

SELECT DateTime, Value, wwFilter

Version 17.0.18000 87
Wonderware Historian Retrieval Guide Data Retrieval Options

FROM History
WHERE TagName = 'Tag1'
AND DateTime >= '2014-01-01 0:00:00.000'
and DateTime < '2014-01-01 1:00:00.000'
and wwFilter = 'SLR()'
In this example, "SLR" stands for "simple linear regression," the algorithm used by Wonderware
Historian to analyze currently stored values and predict other values wit hin the detected trend.

Understanding Retrieval Options

In all retrieval modes, you can adjust which values the historian returns by specifying retrieval options.
The retrieval options are implement ed as special parameters that you set as part of the retrieval q uery.
This section explains each of these options. For an overview of which options apply to which retrieval
modes, see Which Options Apply to Which Retrieval Modes? on page 88.

Which Options Apply to Which Retrieval Modes?


The following table shows which retrieval options apply to which modes. If you specify an option in a
mode where it isn’t applicable, the option is ignored.
Resolution (Values Spaced Every X ms)

Time Deadband (wwTimeDeadband) on


Cycle Count (X Values over Equal Time

Value Deadband (wwValueDeadband)


Intervals ) (wwCycleCount) on page 90

Quality Rule (wwQualityRule) on page

Selecting Values for Analog Summary


Tags (wwValueSelector) on page 124
Timestamp Rule (wwTimestampRule)
History Version (wwVersion) on page

Analog Value Filtering (wwFilter) on


(wwInterpolationType) on page 104

State Calculation (wwStateCalc) on

Predictive Retrieval (wwFilter) (see


"Predictive Filter" on page 87)**
(wwResolution) on page 92

Interpolation Type
on page 100

on page 106

page 118

page 119
page 96

103

111

Cyclic Retrieval on page Y Y Y Y* Y Y Y


29
Delta Retrieval on page Y Y Y Y Y Y Y
32

Full Retrieval on page 37 Y Y Y Y Y

Interpolated Retrieval on Y Y Y Y Y Y Y Y
page 39
Best Fit Retrieval (see Y Y Y Y Y Y Y Y
"Best Fit Retrieval" on
page 43)
Average Ret rieval on Y Y Y Y Y Y Y Y
page 48
Minimum Retrieval on Y Y Y Y Y Y
page 52
Maximum Retrieval on Y Y Y Y Y Y
page 57

88 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

Resolution (Values Spaced Every X ms)

Time Deadband (wwTimeDeadband) on


Cycle Count (X Values over Equal Time

Value Deadband (wwValueDeadband)


Intervals ) (wwCycleCount) on page 90

Quality Rule (wwQualityRule) on page

Selecting Values for Analog Summary


Tags (wwValueSelector) on page 124
Timestamp Rule (wwTimestampRule)
History Version (wwVersion) on page

Analog Value Filtering (wwFilter) on


(wwInterpolationType) on page 104

State Calculation (wwStateCalc) on

Predictive Retrieval (wwFilter) (see


"Predictive Filter" on page 87)**
(wwResolution) on page 92

Interpolation Type
on page 100

on page 106

page 118

page 119
page 96

103

111
Integral Retrieval on Y Y Y Y Y Y Y Y
page 62
Slope Retrieval on page Y Y Y Y
64
Counter Retrieval on Y Y Y Y Y Y
page 66
ValueState Retrieval on Y Y Y Y Y Y Y
page 70
RoundTrip Retrieval on Y Y Y Y Y Y Y
page 76
* - only on Wonderware Historian 9.0 and later
** - only Wonderware Historian 2014 R2 P01 and later

Using Retrieval Options in a Transact-SQL Statement


You can retrieve data in the Wonderware Historian extension tables using normal Transact -SQL code,
as well as the specialized SQL time domain extensions provided by the Wonderware Historian. The
Wonderware Historian extensions provide an easy way to query time-based data from the history
tables. They also provide additional functionality not supported by Trans act -SQL.

Note: The wwP arameters extension is reserved for future use. The wwRowCount parameter is still
supported, but is deprec ated in favor of wwCycleCount.

The extensions are implemented as "virtual" columns in the extension tables. When you query an
extension table, you can specify values for these column parameters to manipulate the dat a that will be
returned. You will need to specify any real-time extension parameters each time that you execute the
query.
For example, you could specify a value for the wwResolution column in the query so that a resolution is
applied to the returned data set:

SELECT DateTime, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND DateTime >= '2001-12-02 10:00:00'
AND DateTime <= '2001-12-02 10:02:00'
AND Value >= 50
AND wwResolution = 10
AND wwRetrievalMode = 'cyclic'
Because the extension tables provide additional functionality that is not possible in a normal SQL
Server, certain limitations apply to the Transact-SQL supported by these tables. For more information,
see Unsupported or Limited Syntax Options on page 21.

Version 17.0.18000 89
Wonderware Historian Retrieval Guide Data Retrieval Options

Although the Microsoft SQL Server may be configured to be case-sensitive, the values for the virtual
columns in the extension tables are always case-insensitive.

Note: You cannot use the IN clause or OR clause to specify more than one condition for a time
domain extension. For example, "wwVersion IN ('original', 'latest')" and
"wwRetrievalMode = 'Delta' OR wwVersion = 'latest'" are not support ed.

For general information on creating SQL queries, see your Microsoft SQL Server documentation.

Cycle Count (X Values over Equal Time Intervals) (wwCycleCount)

In retrieval modes that use cycles, the cycle count determines the number of cycl es for which dat a is
retrieved. The number of actual return values is not always identical with this cycle count. In "truly
cyclic" modes (Cyclic, Interpolated, A verage, and Integral), a single data point is returned for every
cycle boundary. However, in other cycle-based modes (Best Fit, Minimum, Maximum, Counter,
ValueState, and RoundTrip), multiple or no dat a points may be returned for a cycle, depending on the
nature of the dat a.
The length of eac h cycle (the "resolution" of the returned values) is calc ulated as follows:

DC = DQ / (n – 1)
Where DC is the length of the cycle, DQ is the duration of the query, and n is the cycle count.
Instead of specifying a cycle count, you can specify the resolution. In that case, the cycle count is
calculated based on the res olution and the query duration. For more information, see Resolution
(Values Spaced Every X ms) (wwResolution) on page 92.
This option is relevant in the following retrieval modes:
 Cyclic Retrieval on page 29
 Interpolated Retrieval on page 39
 "Best Fit" Retrieval (see "Best Fit Retrieval" on page 43)
 Average Ret rieval on page 48
 Minimum Retrieval on page 52
 Maximum Retrieval on page 57
 Integral Retrieval on page 62
 Counter Retrieval on page 66
 ValueState Retrieval on page 70
 RoundTrip Retrieval on page 76
The application of the cycle count also depends on whether you are querying a wide table. If you are
querying the History table, the cycle count determines the number of rows returned per tag. For
example, a query that applies a cycle count of 20 to two tags will return 40 rows of data (20 rows for
each tag). If you are querying a WideHistory table, the cycle count specifies the total number of rows to
be ret urned, regardless of how many tags were queried. For example, a query that applies a cycle
count of 20 to two tags returns 20 rows of data.
Values chosen:
 If wwRes olution and wwCycleCount are not specified, then a default of 100 cycles are chosen.
 If wwRes olution and wwCycleCount are set to 0, then a default of 100000 cycles are chosen.

90 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

 If wwRes olution and wwCycleCount are both set, then wwCycleCount is ignored.
 If wwCycleCount is specified and is less than 0, then a default of 100 cycles are chosen.
 For ValueState retrieval, if the start time of the cycle is excluded, no states are retur ned for the first
cycle.
 For ValueState retrieval, if the end time of the cycle is excluded, no states are returned for the last
cycle.

Cycle Count - Query Examples


See the following examples of queries that demonstrat e the cycle count beha vior if applied to a single
tag or to multiple tags in the same query:
 Cycle Count - Query 1: Using a Single Tag on page 91
 Cycle Count - Query 2: Using Multiple Tags on page 91

Cycle Count - Query 1: Using a Single Tag


SELECT DateTime, TagName, Value
FROM History
WHERE TagName = 'SysTimeSec'
AND DateTime >= '2001-12-09 11:35'
AND DateTime < '2001-12-09 11:36'
AND wwRetrievalMode = 'Cyclic'
AND wwCycleCount = 300
The results are:

DateTime TagName Value


2001-12-09 11:35:00.000 SysTimeSec 0
2001-12-09 11:35:00.200 SysTimeSec 0
2001-12-09 11:35:00.400 SysTimeSec 0
2001-12-09 11:35:00.600 SysTimeSec 0
...

2001-12-09 11:35:59.200 SysTimeSec 59


2001-12-09 11:35:59.400 SysTimeSec 59
2001-12-09 11:35:59.600 SysTimeSec 59
2001-12-09 11:35:59.800 SysTimeSec 59

Cycle Count - Query 2: Using Multiple Tags


SELECT DateTime, TagName, Value
FROM History
WHERE TagName IN ('SysTimeMin','SysTimeSec')
AND DateTime >= '2001-12-09 11:35'
AND DateTime < '2001-12-09 11:36'
AND wwRetrievalMode = 'Cyclic'
AND wwCycleCount = 300
The results are:

Version 17.0.18000 91
Wonderware Historian Retrieval Guide Data Retrieval Options

DateTime TagName Value


2001-12-09 11:35:00.000 SysTimeMin 35
2001-12-09 11:35:00.000 SysTimeSec 0
2001-12-09 11:35:00.200 SysTimeMin 35
2001-12-09 11:35:00.200 SysTimeSec 0
2001-12-09 11:35:00.400 SysTimeMin 35
2001-12-09 11:35:00.400 SysTimeSec 0
2001-12-09 11:35:00.600 SysTimeMin 35
2001-12-09 11:35:00.600 SysTimeSec 0
...

2001-12-09 11:35:59.200 SysTimeMin 35


2001-12-09 11:35:59.200 SysTimeSec 59
2001-12-09 11:35:59.400 SysTimeMin 35
2001-12-09 11:35:59.400 SysTimeSec 59
2001-12-09 11:35:59.600 SysTimeMin 35
2001-12-09 11:35:59.600 SysTimeSec 59
2001-12-09 11:35:59.800 SysTimeMin 35
2001-12-09 11:35:59.800 SysTimeSec 59

Notice that the values of the two tags are mixed together in the same column.

Resolution (Values Spaced Every X ms) (wwResolution)


In retrieval modes that use cycles, the resolution is the sampling interval for retrieving data, that is, the
length of each cycle.
The number of cycles, therefore, depends on the time period and the resolution:
number of cycles = time period / resolution
The number of actual return values is not always identical with this cycle count. In "truly cyclic" modes
(Cyclic, Interpolated, A verage, and Int egral), a single data point is returned for every cycle boundary.
However, in other cycle-based modes (Best Fit, Minimum, Maximum, Counter, and ValueState),
multiple or no data points may be returned for a cycle, depending on the nat ure of the data.

Note: The rowset is guaranteed to contain one row for eac h tag in the normalized query at every
resolution interval, regardless of whether a physical row exists in history at that particular instance in
time. The value cont ained in the row is the last known physical value in history, at that instant, for the
relevant tag.

Instead of specifying a resolution, you can specify the cycle count directly. In that case, the resolution
is calculated based on the cycle count and the query duration. For more information, see Cycle Count
(X Values over E qual Time Intervals) (wwCycleCount) on page 90.
This option is relevant in the following retrieval modes:
 Cyclic Retrieval on page 29
 Interpolated Retri eval on page 39

92 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

 "Best Fit" Retrieval (see "Best Fit Retrieval" on page 43)


 Average Ret rieval on page 48
 Minimum Retrieval on page 52
 Maximum Retrieval on page 57
 Integral Retrieval on page 62
 Counter Retrieval on page 66
 ValueState Retrieval on page 70
 RoundTrip Retrieval on page 76
For delta retrieval, you can achieve similar res ults by using a time deadband. For more information,
see Time Deadband (wwTimeDeadband) on page 96.

Resolution - Query Example


The following query returns rows that are spaced at 2 sec (2000 msec) intervals over the requested
time period. Dat a is retrieved cyclically.

SELECT DateTime, TagName, Value


FROM History
WHERE TagName IN ('SysTimeMin','SysTimeSec')
AND DateTime >= '2001-12-09 11:35'
AND DateTime <= '2001-12-09 11:36'
AND wwRetrievalMode = 'Cyclic'
AND wwResolution = 2000
The results are:

DateTime TagName Value


2001-12-09 11:35:00.000 SysTimeMin 35
2001-12-09 11:35:00.000 SysTimeSec 0
2001-12-09 11:35:02.000 SysTimeMin 35
2001-12-09 11:35:02.000 SysTimeSec 2
2001-12-09 11:35:04.000 SysTimeMin 35
2001-12-09 11:35:04.000 SysTimeSec 4
2001-12-09 11:35:06.000 SysTimeMin 35
...

2001-12-09 11:35:54.000 SysTimeMin 35


2001-12-09 11:35:54.000 SysTimeSec 54
2001-12-09 11:35:56.000 SysTimeMin 35
2001-12-09 11:35:56.000 SysTimeSec 56
2001-12-09 11:35:58.000 SysTimeMin 35
2001-12-09 11:35:58.000 SysTimeSec 58
2001-12-09 11:36:00.000 SysTimeMin 36
2001-12-09 11:36:00.000 SysTimeSec 0

Version 17.0.18000 93
Wonderware Historian Retrieval Guide Data Retrieval Options

About Phantom Cycles


The phantom cycle is the name given to the cycle that leads up to the query start time. It is used to
calculate which initial value to return at the query start time for all retrieval modes. Some retrieval
modes use the phantom cycle to simply find the las t known value prior to the query start time, whereas
other retrieval modes use the entire cycle to calculate aggregates. The different uses of the phantom
cycle can be seen in the following table.

Simple use of Cycle s not defined, but similar simple Phantom cycle used to calculate
phantom cycle use of time before query start time aggregates

Cyclic Delta Min

Interpolated Full Max

Best Fit Slope A verage

Integral

Counter

ValueState

RoundTrip

It’s common to expect a single aggregate row returned for a particular time interval. You can
accomplish this in several ways.
The following example is querying for hourly averages. It returns a single row time stamped at the
query start time. If the query included the query end point by including an equal sign for it, the query
would also have returned an additional row at the qu ery end time.

SELECT DateTime, Value, Quality, QualityDetail, OPCQuality


FROM History
WHERE TagName IN ('SysTimeSec')
AND DateTime >= '2009-10-16 08:00:00'
AND DateTime < '2009-10-16 09:00:00'
AND wwRetrievalMode = 'Avg'
AND wwResolution = 3600000
The results are:

DateTime Value Quality QualityDetail OPCQuality


2015-10-16 08:00:00.0000000 29.5 0 192 192

What may be confusing in this example is the calculation of the average in the returned row for the
phantom cycle leading up to the query start time. The query specifies a positive one hour time interval
between the query start time and the query end time. You may therefore expect that the calculated and
returned average should be for the specified interval.

94 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

However, the time difference bet ween start and end time in the above query is not actually required
because the resolution is provided explicitly (wwResolution = 36000000). If the query specified an end
time equal to the specified start time and if it included the equal sign for the end time, the query would
still return the same single row of data.

SELECT DateTime, Value, Quality, QualityDetail as QD, OPCQuality


FROM History
WHERE TagName IN ('SysTimeSec')
AND DateTime >= '2015-10-16 08:00:00'
AND DateTime <= '2015-10-16 09:00:00'
AND wwRetrievalMode = 'Avg'
AND wwCycleCount = 1
The results are:

DateTime Value Quality QualityDetail OPCQuality


2015-10-16 08:00:00.0000000 29.5 0 192 192

This second example also asks for hourly averages and it also returns only a single row of dat a
stamped at the query start time. This query, however, must specify a time difference between the st art
and end time, because the resolution is not explicitly defined in the query.
As in the preceding query, the specified interval and cycle count of 1 may look like the returned row
has been calculated for the specified interval, but the returned row is once again for the phantom cycle
leading up to the start time.
For some queries, you may want to be certain to include values on a cycle boundary. For example, the
following query is looking for a minimum value wit hin a cycle. In this query, the beginning D ateTime
statement uses ">=" to ensure that the entire cycle is queried. E ven if the minimum value happens to
be at the beginning of the cycle, the following query will provide an accurate result:

SELECT StartDateTime, *
FROM History
WHERE TagName = 'SysTimeSec'
AND DateTime >= '2016-03-31 15:41:10'
AND DateTime < '2016-03-31 15:41:20'
AND wwRetrievalMode = 'Min'
AND Quality <> 133
AND wwCycleCount = 1

The StartDateTime makes it easier to see which time interval was used to calculate the returned
aggregate. This column returns the time stamp of the beginning of the cycle used for the aggregat e
calculation. The time stamp is always returned in accordance with the specified time zone and always
has the same offset as the time stamp returned in the DateTime column, even when the two time
stamps are on different sides of a DS T change.
Assuming results are timestamped at the end of the cycle (as is done by default when
wwTimeStampRule is set to END), the initial rows in the examples above would return a DateTime
equal to '2009-10-16 08:00:00', and the Start DateTime column would return '2009-10-16 07:00:00'
making it easy to interpret the result.
If instead the query were to ask for results time stamped at the beginning of the cycle with
wwTimeStampRule set to STA RT, the initial rows in the same examples would still return a DateTime
equal to '2009-10-16 08:00:00', but the time stamp has now been shifted in accor dance with the time
stamp request. The res ult is therefore calculated for the specified time interval between 8 a.m. and 9
a.m. In this example, the new StartDat eTime column would return the same time stamp as the
DateTime column, '2009-10-16 08:00:00', again making it easier to interpret the result.

Version 17.0.18000 95
Wonderware Historian Retrieval Guide Data Retrieval Options

For retrieval modes for which cycles are defined, the Start DateTime column returns the cycle start
time. These modes are:
 Cyclic Retrieval on page 29
 Interpolated Retrieval on page 39
 "Best Fit" Retrieval (see "Best Fit Retrieval" on page 43)
 Average Ret rieval on page 48
 Minimum Retrieval on page 52
 Maximum Retrieval on page 57
 Integral Retrieval on page 62
 Counter Retrieval on page 66
 ValueState Retrieval on page 70
 RoundTrip Retrieval on page 76
In the remaining retrieval modes, the StartDat eTime column ret urns the same time stamp as the
DateTime column.
For an additional ex ample, see Querying Aggregat e Data in Different Ways on page 168.

Time Deadband (wwTimeDeadband)


A time deadband for retrieval controls the time res olution of data ret urned in delta mode. Any value
changes that occur within the time deadband are not returned.
Time deadbands can be applied to analog, discret e, and string tags.
The deadband "base value" is reset each time that a value is returned, so that the last value returned
acts as the basis for the deadband.
The following illustration shows an example of applying a time deadband:

96 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

Data is retrieved for the time period starting with TS and ending with TE. All points in the graphic
represent data values stored on the historian. The grey areas represent the time deadband, which
starts anew with every returned value. Only the green points (P 2, P4, P7, P8, P9, P11) are returned. The
other points are not returned because they fall wit hin a deadband.

Time Deadband - Query Examples

To apply a time deadband, set the wwTimeDeadband parameter in your query.


For examples, see the following:
 Time Deadband - Query 1 on page 97
 Time Deadband - Query 2 on page 98
 Time Deadband - Query 3 on page 99

Note: All of these example queries return dat a values for the analog tag 'SysTimeSec'.

Time Deadband - Query 1


This query specifies to only ret urn data that changed during a 5 second time deadband.

SELECT DateTime, TagName, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND DateTime >= '2001-12-09 11:35'
AND DateTime <= '2001-12-09 11:37'
AND wwRetrievalMode = 'Delta'
AND wwTimeDeadband = 5000
The results are:

DateTime TagName Value


2001-12-09 11:35:00.000 SysTimeSec 0
2001-12-09 11:35:06.000 SysTimeSec 6
2001-12-09 11:35:12.000 SysTimeSec 12
2001-12-09 11:35:18.000 SysTimeSec 18
2001-12-09 11:35:24.000 SysTimeSec 24
2001-12-09 11:35:30.000 SysTimeSec 30
2001-12-09 11:35:36.000 SysTimeSec 36
2001-12-09 11:35:42.000 SysTimeSec 42
2001-12-09 11:35:48.000 SysTimeSec 48
2001-12-09 11:35:54.000 SysTimeSec 54
2001-12-09 11:36:00.000 SysTimeSec 0
2001-12-09 11:36:06.000 SysTimeSec 6
2001-12-09 11:36:12.000 SysTimeSec 12
2001-12-09 11:36:18.000 SysTimeSec 18

Version 17.0.18000 97
Wonderware Historian Retrieval Guide Data Retrieval Options

2001-12-09 11:36:24.000 SysTimeSec 24


2001-12-09 11:36:30.000 SysTimeSec 30
2001-12-09 11:36:36.000 SysTimeSec 36
2001-12-09 11:36:42.000 SysTimeSec 42
2001-12-09 11:36:48.000 SysTimeSec 48
2001-12-09 11:36:54.000 SysTimeSec 54
2001-12-09 11:37:00.000 SysTimeSec 0

Time Deadband - Query 2


This query specifies to only ret urn data that changed during a 4900 millisecond time deadband.

SELECT DateTime, TagName, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND DateTime >= '2001-12-09 11:35'
AND DateTime <= '2001-12-09 11:37'
AND wwRetrievalMode = 'Delta'
AND wwTimeDeadband = 4900
The results are:

DateTime TagName Value


2001-12-09 11:35:00.000 SysTimeSec 0
2001-12-09 11:35:05.000 SysTimeSec 5
2001-12-09 11:35:10.000 SysTimeSec 10
2001-12-09 11:35:15.000 SysTimeSec 15
2001-12-09 11:35:20.000 SysTimeSec 20
2001-12-09 11:35:25.000 SysTimeSec 25
2001-12-09 11:35:30.000 SysTimeSec 30
2001-12-09 11:35:35.000 SysTimeSec 35
2001-12-09 11:35:40.000 SysTimeSec 40
2001-12-09 11:35:45.000 SysTimeSec 45
2001-12-09 11:35:50.000 SysTimeSec 50
2001-12-09 11:35:55.000 SysTimeSec 55
2001-12-09 11:36:00.000 SysTimeSec 0
2001-12-09 11:36:05.000 SysTimeSec 5
2001-12-09 11:36:10.000 SysTimeSec 10
2001-12-09 11:36:15.000 SysTimeSec 15
2001-12-09 11:36:20.000 SysTimeSec 20
2001-12-09 11:36:25.000 SysTimeSec 25
2001-12-09 11:36:30.000 SysTimeSec 30

98 Version 17.0.18000
Data Retrieval Options Wonderware Historian Retrieval Guide

2001-12-09 11:36:35.000 SysTimeSec 35


2001-12-09 11:36:40.000 SysTimeSec 40
2001-12-09 11:36:45.000 SysTimeSec 45
2001-12-09 11:36:50.000 SysTimeSec 50
2001-12-09 11:36:55.000 SysTimeSec 55
2001-12-09 11:37:00.000 SysTimeSec 0

Time Deadband - Query 3


This query specifies to only ret urn data that changed during a 2000 millisecond time deadband.

SELECT DateTime, TagName, Value


FROM History
WHERE TagName IN ('SysTimeSec','SysTimeMin')
AND DateTime >= '2001-12-09 11:35'
AND DateTime <= '2001-12-09 11:36'
AND wwRetrievalMode = 'Delta'
AND wwTimeDeadband = 2000
The results are:

DateTime TagName Value


2001-12-09 11:35:00.000 SysTimeSec 0
2001-12-09 11:35:00.000 SysTimeMin 35
2001-12-09 11:35:03.000 SysTimeSec 3
2001-12-09 11:35:06.000 SysTimeSec 6
2001-12-09 11:35:09.000 SysTimeSec 9
2001-12-09 11:35:12.000 SysTimeSec 12
2001-12-09 11:35:15.000 SysTimeSec 15
2001-12-09 11:35:18.000 SysTimeSec 18
2001-12-09 11:35:21.000 SysTimeSec 21
2001-12-09 11:35:24.000 SysTimeSec 24
2001-12-09 11:35:27.000 SysTimeSec 27
2001-12-09 11:35:30.000 SysTimeSec 30
2001-12-09 11:35:33.000 SysTimeSec 33
2001-12-09 11:35:36.000 SysTimeSec 36
2001-12-09 11:35:39.000 SysTimeSec 39
2001-12-09 11:35:42.000 SysTimeSec 42
2001-12-09 11:35:45.000 SysTimeSec 45
2001-12-09 11:35:48.000 SysTimeSec 48
2001-12-09 11:35:51.000 SysTimeSec 51

Version 17.0.18000 99
Wonderware Historian Retrieval Guide Data Retrieval Options

2001-12-09 11:35:54.000 SysTimeSec 54


2001-12-09 11:35:57.000 SysTimeSec 57
2001-12-09 11:36:00.000 SysTimeSec 0
2001-12-09 11:36:00.000 SysTimeMin 36

Value Deadband (wwValueDeadband)


A value deadband for ret rieval controls the value resolution of data returned in delta mode. Any dat a
values that change less than the specified deadband are not returned. The deadband is a percentage
of a tag’s full scale in engineering units.
The deadband "base value" is reset each time that a value is returned, so that the last value returned
acts as the basis for the deadband.
Changes in quality will force a value to be returned even if the value deadband has not been met.
The following illustration shows an example of applying a value deadband:

Data is retrieved for the time period starting with TS and ending with TE. All points in the graphic
represent data values stored on the historian. The gray areas represent the value deadband, which
starts anew with every returned value. Only the green points (P 2, P5, P6, P7, P9, P10, P11) are ret urned.
The other points are not returned because they fall within a deadband.

Value Deadband - Query Examples


See the following examples of queries that use value deadband:
 Value Deadband - Query 1 on page 101
 Value Deadband - Query 2 on page 101

Note: Each of these ex amples returns data values for the analog tag 'Sys TimeSec '. The minimum
engineering unit for 'Sys TimeS ec' is 0, and the maximum engineering unit is 59.

100 Version 17.0.18000


Data Retrieval Options Wonderware Historian Retrieval Guide

Value Deadband - Query 1


This query specifies to return only data that changed by more than 10 percent of the tag's full
engineering unit range. Using a value deadband of 10 perc ent equates to an absolute change of 5.9 for
'SysTimeS ec.'

SELECT DateTime, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND DateTime >= '2001-12-09 11:35'
AND DateTime <= '2001-12-09 11:37'
AND wwRetrievalMode = 'Delta'
AND wwValueDeadband = 10
The results are:

DateTime Value
2001-12-09 11:35:00.000 0
2001-12-09 11:35:06.000 6
2001-12-09 11:35:12.000 12
2001-12-09 11:35:18.000 18
2001-12-09 11:35:24.000 24
2001-12-09 11:35:30.000 30
2001-12-09 11:35:36.000 36
2001-12-09 11:35:42.000 42
2001-12-09 11:35:48.000 48
2001-12-09 11:35:54.000 54
2001-12-09 11:36:00.000 0
2001-12-09 11:36:06.000 6
2001-12-09 11:36:12.000 12
2001-12-09 11:36:18.000 18
2001-12-09 11:36:24.000 24
2001-12-09 11:36:30.000 30
2001-12-09 11:36:36.000 36
2001-12-09 11:36:42.000 42
2001-12-09 11:36:48.000 48
2001-12-09 11:36:54.000 54
2001-12-09 11:37:00.000 0

Value Deadband - Query 2


This query specifies to only ret urn data that changed by more than 5 percent of the tag's full
engineering unit range. Using a value deadband of 5 percent equates to an absolute change of 2.95 for
'SysTimeS ec.'

Version 17.0.18000 101


Wonderware Historian Retrieval Guide Data Retrieval Options

SELECT DateTime, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND DateTime >= '2001-12-09 11:35'
AND DateTime <= '2001-12-09 11:37'
AND wwRetrievalMode = 'Delta'
AND wwValueDeadband = 5
The results are:

DateTime Value
2001-12-09 11:35:00.000 0
2001-12-09 11:35:03.000 3
2001-12-09 11:35:06.000 6
2001-12-09 11:35:09.000 9
2001-12-09 11:35:12.000 12
2001-12-09 11:35:15.000 15
2001-12-09 11:35:18.000 18
2001-12-09 11:35:21.000 21
2001-12-09 11:35:24.000 24
2001-12-09 11:35:27.000 27
2001-12-09 11:35:30.000 30
2001-12-09 11:35:33.000 33
2001-12-09 11:35:36.000 36
2001-12-09 11:35:39.000 39
2001-12-09 11:35:42.000 42
2001-12-09 11:35:45.000 45
2001-12-09 11:35:48.000 48
2001-12-09 11:35:51.000 51
2001-12-09 11:35:54.000 54
2001-12-09 11:35:57.000 57
2001-12-09 11:36:00.000 0
2001-12-09 11:36:03.000 3
2001-12-09 11:36:06.000 6
2001-12-09 11:36:09.000 9
2001-12-09 11:36:12.000 12
2001-12-09 11:36:15.000 15
2001-12-09 11:36:18.000 18
2001-12-09 11:36:21.000 21
2001-12-09 11:36:24.000 24

102 Version 17.0.18000


Data Retrieval Options Wonderware Historian Retrieval Guide

2001-12-09 11:36:27.000 27
2001-12-09 11:36:30.000 30
2001-12-09 11:36:33.000 33
2001-12-09 11:36:36.000 36
2001-12-09 11:36:39.000 39
2001-12-09 11:36:42.000 42
2001-12-09 11:36:45.000 45
2001-12-09 11:36:48.000 48
2001-12-09 11:36:51.000 51
2001-12-09 11:36:54.000 54
2001-12-09 11:36:57.000 57
2001-12-09 11:37:00.000 0

History Version (wwVersion)

The Wonderware Historian allows you to overwrite a stored tag value with later versions of the value.
The original version of the value is still maintained, so that effectively, multiple versions of the tag value
exist at the same point in time.
When ret rieving data, you can specify whether to retrieve the originally stored version or the latest
version that is available. To do this, set the history version option to "Original" for the original version or
"Latest" for the lat est available version. If you do not specify the version, the latest version is returned.
To distinguish between a latest value and an original value, the historian returns a special QualityDetail
value of 202 for a latest point with good quality.
This option is relevant in all ret rieval modes.

History Version - Query Example


This example illustrates using history version. First, consider this query:

SELECT TagName, DateTime, Value, wwVersion


FROM History
WHERE TagName IN ('SysTimeHour', 'SysTimeMin')
AND DateTime >= '2001-12-20 0:00'
AND DateTime <= '2001-12-20 0:05'
AND wwRetrievalMode = 'Delta'
AND wwVersion = 'Original'
The results are:

TagName DateTime Value wwVersion


SysTimeMin 2001-12-20 00:00:00.000 0 ORIGINAL
SysTimeHour 2001-12-20 00:00:00.000 0 ORIGINAL
SysTimeMin 2001-12-20 00:01:00.000 1 ORIGINAL

Version 17.0.18000 103


Wonderware Historian Retrieval Guide Data Retrieval Options

SysTimeMin 2001-12-20 00:02:00.000 2 ORIGINAL


SysTimeMin 2001-12-20 00:03:00.000 3 ORIGINAL
SysTimeMin 2001-12-20 00:04:00.000 4 ORIGINAL
SysTimeMin 2001-12-20 00:05:00.000 5 ORIGINAL

When ret rieving the latest version, the wwVersion parameter always returns with a value of LA TES T
for all values, even though many of the values may actually be the original values that came from the
I/O Server. To distinguis h between an actual latest value and an original value, a special QualityDetail
of 202 is returned for a good, latest point.
For example:

SELECT DateTime, Value, Quality, QualityDetail, OPCQuality, wwVersion


FROM History
WHERE TagName IN ('PV')
AND DateTime >= '2005-04-17 11:35:00'
AND DateTime <= '2005-04-17 11:36:00'
AND wwRetrievalMode = 'Delta'
AND wwVersion = 'Latest'
The results are:

DateTime Value Quality QualityDetail OPCQuality wwVersion


2005-04-17 12.5 0 192 192 LATEST
11:35:00.000
2005-04-17 17.3 0 192 192 LATEST
11:35:15.000
2005-04-17 34.0 0 202 192 LATEST
11:35:30.000
2005-04-17 43.1 0 192 192 LATEST
11:35:45.000
2005-04-17 51.2 0 192 192 LATEST
11:36:00.000

Interpolation Type (wwInterpolationType)

For various retrieval modes, you can control how analog tag values at cycle boundaries are calculated
if there is no actual value stored at that point in time. The options are as follows:

104 Version 17.0.18000


Data Retrieval Options Wonderware Historian Retrieval Guide

 Stairstep: No int erpolation occurs. The value at the cycle boundary is assumed to be the same
value as the last stored value before the cycle boundary. The last known point is returned with the
given cycle time. If no valid value can be found, a NULL is ret urned.

 Linear: The historian calculates a new value at the cycle boundary by interpolating bet ween the
last stored value before the boundary and the first stored value after the bo undary. If either of
these values is NULL, it returns the last stored value before the boundary.
Expressed as a formula, V c is calculated as:
Vc = V1 + ((V2 - V1) * ((Tc - T1) / (T2 - T1)))

The type of data that you want to retrieve usually determines the interpolation type to use. For
example, if you have a thermocouple, the temperature change is linear, so it’s best to use linear
interpolation. If you have a tag that contains discrete measurements, such as a set point, then you
probably want to use stair-stepped values. In general, it is recommended that you use linear
interpolation as the general setting, and use stair-stepped values for the exceptions.
This option is relevant in the following retrieval modes:
 Interpolated Retrieval
 "Best Fit" Retrieval
 Average Ret rieval on page 48
 Integral Retrieval on page 62
The quality of an interpolated point is determined by the wwQualityRule setting. For more information,
see Qualit y Rule (wwQualityRule) on page 111.

Version 17.0.18000 105


Wonderware Historian Retrieval Guide Data Retrieval Options

The interpolation type can be set on three levels:


 The Wonderware Historian system-wide setting. The system-wide setting must be either stair-step
or interpolated. For more information, see "System Parameters" on page 36. This setting is
configured using the Wonderware Historian Configuration Editor.
 The individual analog tag setting. You can configure an individual analog tag to use the
system-wide setting or either stair-stepped values or linear interpolation. The individual tag setting
will override the system-wide setting. This setting is configured using the Wonderware Historian
Configuration Editor.
 The setting for the wwInterpolationType parameter in the query. This setting overrides any other
setting for all tags in the query.
The wwInterpolationTy pe parameter is dynamically used bot h for input for the query, when you need to
override the individual tag settings, and for output for each individual row to show whether a particular
row value was calculated using linear interpolation (returned as "LINEA R") or if it is a s tair-stepped
value (returned as "STA IRS TEP").
To force a query to always use linear interpolation whenever applicable, specify the following in the
query:

AND wwInterpolationType = 'Linear'


To force a query to always return stair-stepped values, specify the following in the query:

AND wwInterpolationType = 'StairStep'

Timestamp Rule (wwTimestampRule)

For various cycle-based retrieval modes, you can control whether the returned values are timestamped
at the beginning or at the end of each cycle.
To force a query to timestamp results at the start of a cycle, specify the following in the query:

AND wwTimeStampRule = 'Start'


To force a query to timestamp results at the end of a cycle, specify the following in the query:

AND wwTimeStampRule = 'End'


If you include the wwTimeStampRule column in your SELECT statement, it will show which tim estamp
rule has been applied for the individual row, if applicable.
The options are as follows:
 Start: The value for a given cycle is stamped with the cycle start time. For example, in the
following illustration of a cyclic query, the following values are ret urned at the cycle boundaries:
o At TC0: P7, because it falls on the cycle boundary. In cyclic mode, if there is a value right on the
cycle boundary, it is considered to belong to the cycle before the boundary. In this case, this is
the cycle starting at TC0 and ending at TC1, and because the Start timestamp rule is used, the
value is timestamped at TC0.
o At TC1: P11, because it is the last value in the cycle starting at TC1 and ending at TC2

106 Version 17.0.18000


Data Retrieval Options Wonderware Historian Retrieval Guide

o At TC2: The last value in the "phant om" cycle starting at TC2

 End: The value for a given cycle is stamped with the cycle end time. For ex ample, in the following
illustration of a cyclic query, the following values are returned at the cycle boundaries:
o At TC0: P1, because it is the last value in the "phantom" cycle ending at TC0. Because the End
timestamp rule is used, the value is timestamped at TC0.
o At TC1: P7, because it falls on the cycle boundary. In cyclic mode, if there is a value right on the
cycle boundary, it is considered to belong to the cycle before the boundary. In this case, this is
the cycle starting at TC0 and ending at TC1, and because the End timestamp rule is used, the
value is timestamped at TC1.
o At TC2: P11, because it is the last value in the cycle ending at TC2

Version 17.0.18000 107


Wonderware Historian Retrieval Guide Data Retrieval Options

108 Version 17.0.18000


Data Retrieval Options Wonderware Historian Retrieval Guide

 Server default: Either Start or End is used, depending on the system parameter setting on the
Wonderware Historian.
This option is relevant in the following retrieval modes:
 Cyclic Retrieval on page 29 (Wonderware Historian 9.0 and later)
 Interpolated Retrieval on page 39
 Average Ret rieval on page 48
 Integral Retrieval on page 62

Version 17.0.18000 109


Wonderware Historian Retrieval Guide Data Retrieval Options

 Counter Retrieval on page 66


 ValueState Retrieval on page 70
 RoundTrip Retrieval on page 76

Time Zone (wwTimeZone)


For Wonderware Historian version 8.0 and later, all history data is stored in Coordinated Universal
Time (UTC). The wwTimeZone extension allows you to specify the time zone to be used for the
timestamps of the returned data values. The Retrieval subsystem will convert the timestamps to local
time in the specified time zone.
The wwTimeZone extension may be assigned any of the values stored in the TimeZone column of the
TimeZone table in the Runtime database. In addition to specifying the name of the timezone in the
wwTimeZone parameter, you can also specify the TimeZoneID (as a string). For example, on a typical
US English system, specifying " wwTimeZone = 'Mountain Standard Time' " and " wwTimeZone
= '64'" yields the same result.
The TimeZone table is repopulated at every system start up from Microsoft operating system registry
entries, and will therefore reflect the time zones available from the server operating system, including
any new or custom time zones which might be added by operating system service packs or installed
software.
The Retrieval subsystem will automatically correct for daylight savings time in the requested time zone.
When computing daylight savings and time zone parameters, the settings of the server operating
system are used. The Retrieval subsystem does not provide any means for using client -side settings.
If wwTimeZone is not specified, the time zone for retrieval defaults to the time zone of the Wonderware
Historian comput er.
For example:

SELECT TagName, DateTime, Value, wwTimeZone


FROM History
WHERE TagName IN ('SysTimeHour', 'SysTimeMin')
AND DateTime >= '2001-12-20 0:00'
AND DateTime <= '2001-12-20 0:05'
AND wwRetrievalMode = 'Delta'
AND wwTimeZone = 'W. Europe Standard Time'
The results are:

TagName DateTime Value wwTimeZone


SysTimeMin 2001-12-20 00:00:00.000 0 W. Europe Standard Time
SysTimeHour 2001-12-20 00:00:00.000 15 W. Europe Standard Time
SysTimeMin 2001-12-20 00:01:00.000 1 W. Europe Standard Time
SysTimeMin 2001-12-20 00:02:00.000 2 W. Europe Standard Time
SysTimeMin 2001-12-20 00:03:00.000 3 W. Europe Standard Time
SysTimeMin 2001-12-20 00:04:00.000 4 W. Europe Standard Time
SysTimeMin 2001-12-20 00:05:00.000 5 W. Europe Standard Time

If you are using date/time functions and the wwTimeZone parameter, you will need to use the
faaTZgetdate() function.

110 Version 17.0.18000


Data Retrieval Options Wonderware Historian Retrieval Guide

Quality Rule (wwQualityRule)


The quality rule can be used to specify whether values wit h certain characteristics are explicitly
excluded from consideration by data retrieval. This parameter will override the setting of the
QualityRule system parameter. Valid values are GOOD, E XTENDE D, or OP TIMIS TIC.
 A quality rule of GOOD means that data values with uncertain (64) OPC quality are not used in the
retrieval calculations and are ignored. Values with bad QualityDetail indicat e gaps in the data.
 A quality rule of E XTE NDED means that data values with both good and uncert ain OP C quality are
used in the retrieval calculations. Values with bad QualityDetail indicate gaps in the data.
 A quality rule of OP TIMIS TIC means that calculations that include some good and some NULL
values do not cause the overall calculations to return NULL.
You can apply a quality rule to all retrieval modes.
The OP TIMIS TIC setting for the quality rule lets you retrieve information that is possibly incomplete but
may nevertheless provide better results where the calculation cycle contains data gaps. This setting
calculates using the last known good value prior to the gap (if possible). The logic for determining the
quality of the points returned remains unchanged. The integral retrieval mode is an exception to this
where the integral is scaled up to cover gaps. For more information, see Integral Retrieval on page 62.
The following figure shows a counter retrieval situation in which three of the four shown cycle
boundaries are located in data gaps. Without using OP TIMIS TIC, counter queries would return a NULL
at all cycle boundaries because the mode needs valid good values at each end of the cycle calculate a
precise difference.

If the query were to specify OP TIMIS TIC, the counter mode will always return rows with numeric
counter values and good quality. These rows may or may not be precise. The Perc entGood column of
the row returns the percentage of time in each cycle in which retrieval was able to find values stored
with good quality, so if the Percent Good is anything less than 100, then the returned row may be
incorrect. Quality is returned as uncertain if percent good is not 100 percent.
Now look at the counter values that are returned using OP TIMIS TIC quality in the preceding
illustration. The query skips the value to be ret urned at the first cycle boundary, because there is not
enough information about the cycle prior to that boundary. At the second cycle boundary, the value 0
will be returned, because there was a gap in the data for the entire first cycle. In the second cycle,
there are two points, P1 and P2. The q uery uses P2 as the end value of the cycle and infers a start
value of the cycle from P1. At the third cycle boundary, Tc2, the query returns P2 – P1. Similarly, at the
last cycle boundary, the query returns P4 – P3.

Version 17.0.18000 111


Wonderware Historian Retrieval Guide Data Retrieval Options

For the integral retrieval mode, the qu ery does not summarize data for gaps becaus e there is no way
to know which value to use for the summarization. However, if the query specifies OP TIMIS TIC quality,
the query uses the last known good value for the summarization in the gap. As described for t he
counter retrieval example, the PercentGood column also expresses the quality of the calculated value
in integral ret rieval, so if the PercentGood is anything less than 100, then the returned row may be
incorrect.

Quality Rule - Query Examples


To force a query to exclude points with doubtful OPC quality, specify the following in the query:

AND wwQualityRule = 'Good'


To force a query to use points with bot h good and doubt ful OP C quality, specify the following in the
query:

AND wwQualityRule = 'Extended'


For examples, see the following:
 Qualit y Rule - Query 1 on page 112
 Qualit y Rule - Query 2 on page 113
 Qualit y Rule - Query 3 on page 114
 Qualit y Rule - Query 4 on page 114
 Qualit y Rule - Query 5 on page 115
 Qualit y Rule - Query 6 on page 116
 Qualit y Rule - Query 7 on page 117
 Qualit y Rule - Query 8 on page 117

Quality Rule - Query 1


If you include the wwQualityRule column in a SELECT statement, it will show which quality rule was
used for the individual row, if applicable.
You can combine OP C qualities in a query. For example, if you combine a mixture of good OP C
qualities (such as 192 to 219), a good OPC quality (192) will be returned as a combined result.

SELECT TagName, DateTime, Value, QualityDetail, OPCQuality, wwRetrievalMode


FROM History
WHERE TagName = 'I0R5'
AND DateTime >= '2009-09-12 00:20'
AND DateTime <= '2009-09-12 00:40'
AND wwResolution = 10000
AND wwRetrievalMode = 'Avg'
If you run this query against the following sample data:

Tagname DateTime Resolution QualityDetail


I0R5 2009-09-12 00:07 2 193
I0R5 2009-09-12 00:14 3 195
I0R5 2009-09-12 00:22 0 196
I0R5 2009-09-12 00:25 1 199
I0R5 2009-09-12 00:27 0 200

112 Version 17.0.18000


Data Retrieval Options Wonderware Historian Retrieval Guide

Tagname DateTime Resolution QualityDetail


I0R5 2009-09-12 00:29 2 207
I0R5 2009-09-12 00:33 3 215
I0R5 2009-09-12 00:36 0 216
I0R5 2009-09-12 00:39 1 219

The results are:

Tagname DateTime Value QualityD OPCQuality wwRetrievalMode


etail
I0R5 2009-09-12 00:20 2.6 192 192 AVERAGE
I0R5 2009-09-12 00:30 1.0 192 192 AVERAGE
I0R5 2009-09-12 00:40 1.6 192 192 AVERAGE

Quality Rule - Query 2


Similar to Quality Rule - Query 1 on page 112, if you combine a mixture of doubt ful OP C qualities, a
doubtful OPC quality (64) will be returned as the combined OPC quality.

SELECT TagName, DateTime, Value, QualityDetail, OPCQuality, wwRetrievalMode


FROM History
WHERE TagName = 'I0R5'
AND DateTime >= '2009-09-12 00:20'
AND DateTime <= '2009-09-12 00:40'
AND wwResolution = 10000
AND wwRetrievalMode = 'Integral'
If you run this query against the following sample data:

Tagname DateTime Resolution QualityDetail


I0R5 2009-09-12 00:07 2 65
I0R5 2009-09-12 00:14 3 68
I0R5 2009-09-12 00:22 0 71
I0R5 2009-09-12 00:25 1 74
I0R5 2009-09-12 00:27 0 79
I0R5 2009-09-12 00:29 2 80
I0R5 2009-09-12 00:33 3 88
I0R5 2009-09-12 00:36 0 92
I0R5 2009-09-12 00:39 1 64

The results are:

Tagname DateTime Value QualityDetail OPCQuality wwRetrievalMode


I0R5 00:20 26.0 64 64 INTEGRAL
I0R5 00:30 10.0 64 64 INTEGRAL

Version 17.0.18000 113


Wonderware Historian Retrieval Guide Data Retrieval Options

Tagname DateTime Value QualityDetail OPCQuality wwRetrievalMode


I0R5 00:40 16.0 64 64 INTEGRAL

Quality Rule - Query 3


When you combine the same OPC quality then that OPC quality will be ret urned. However, when there
is no good point in a cycle for cyclic modes such as Integral, A verage, Counter, or AnalogS ummary,
the returned NULL value will have an OPC quality of 0 and a Quality Detail of 65536, regardless of
combined qualities.

SELECT TagName, StartDateTime, EndDateTime, OPCQuality, PercentGood,


wwRetrievalMode, first
FROM AnalogSummaryHistory
WHERE TagName = 'F0R5'
AND StartDateTime >= '2009-09-12 00:20'
AND EndDateTime <= '2009-09-12 00:40'
AND wwResolution = 10000
AND wwRetrievalMode = 'Cyclic'
If you run this query against the following sample data:

Tagname DateTime Resolution QualityDetail


F0R5 2009-09-12 00:07 1.6 78
F0R5 2009-09-12 00:14 3.1 78
F0R5 2009-09-12 00:22 0.2 78
F0R5 2009-09-12 00:25 0.8 78
F0R5 2009-09-12 00:27 0.4 78
F0R5 2009-09-12 00:29 2.2 78
F0R5 2009-09-12 00:33 3.3 78
F0R5 2009-09-12 00:36 0.3 78
F0R5 2009-09-12 00:39 1.2 78

The results are:

Tagname StartDate EndDate Time OPCQuali Percent wwRetrievalMode first


Time ty Good
F0R5 2009-09-12 2009-09-12 78 100 CYCLIC 0.200
00:20 00:30
F0R5 2009-09-12 2009-09-12 78 100 CYCLIC 3.300
00:30 00:40

Quality Rule - Query 4


SELECT TagName, DateTime, Value, QualityDetail, OPCQuality, wwRetrievalMode
FROM History
WHERE TagName = 'F0R5'
AND DateTime >= '2009-09-12 00:20'
AND DateTime <= '2009-09-12 00:40'
AND wwResolution = 10000
AND wwRetrievalMode = 'Avg'

114 Version 17.0.18000


Data Retrieval Options Wonderware Historian Retrieval Guide

If you run this query against the following sample data:

Tagname DateTime Resolution QualityDetail


F0R5 2009-09-12 00:07 1.6 15
F0R5 2009-09-12 00:14 3.1 15
F0R5 2009-09-12 00:22 0.2 15
F0R5 2009-09-12 00:25 0.8 15
F0R5 2009-09-12 00:27 0.4 15
F0R5 2009-09-12 00:29 2.2 15
F0R5 2009-09-12 00:33 3.3 15
F0R5 2009-09-12 00:36 0.3 15
F0R5 2009-09-12 00:39 1.2 15

The results are:

Tagname DateTime Value QualityD OPCQuality wwRetrievalMode


etail
F0R5 2009-09-12 00:20 NULL 65536 0 AVERAGE
F0R5 2009-09-12 00:30 NULL 65536 0 AVERAGE
F0R5 2009-09-12 00:40 NULL 65536 0 AVERAGE

Quality Rule - Query 5


When you combine a mixture of good, bad, and uncert ain OP C qualities, a doubt ful OP C quality (64)
will be returned as a combined res ult.

SELECT TagName, DateTime, Value, QualityDetail, OPCQuality, wwRetrievalMode


FROM History
WHERE TagName = 'F0R5'
AND DateTime >= '2009-09-12 00:20'
AND DateTime <= '2009-09-12 00:40'
AND wwResolution = 10000
AND wwRetrievalMode = 'Avg'
AND wwQualityRule = 'Optimistic'
If you run this query against the following sample data:

Tagname DateTime Resolution QualityDetail


F0R5 2009-09-12 00:07 1.6 15
F0R5 2009-09-12 00:14 3.1 69
F0R5 2009-09-12 00:22 0.2 78
F0R5 2009-09-12 00:25 0.8 200
F0R5 2009-09-12 00:27 0.4 15
F0R5 2009-09-12 00:29 2.2 92
F0R5 2009-09-12 00:33 3.3 88

Version 17.0.18000 115


Wonderware Historian Retrieval Guide Data Retrieval Options

Tagname DateTime Resolution QualityDetail


F0R5 2009-09-12 00:36 0.3 199
F0R5 2009-09-12 00:39 1.2 196

The results are:

Tagname DateTime Value QualityD OPCQuality wwRetrievalMode


etail
F0R5 2009-09-12 00:20 2.012 64 64 AVERAGE
F0R5 2009-09-12 00:30 0.820 64 64 AVERAGE
F0R5 2009-09-12 00:40 1.751 64 64 AVERAGE

Quality Rule - Query 6


For RoundTrip, StateSummary, and ValueState modes, the OP C qualities are only combined with the
same state in a cycle. If the state only occurs once in a cycle, then the qualities of that state will be
returned. The returned NULL state will always have an OPC quality of 0 and Quality Detail of 65536.
The same qualities are returned for a state that has no roundtrip in RoundTrip mode.

SELECT TagName, DateTime, Value, QualityDetail, OPCQuality, StateTime


FROM History
WHERE TagName = 'I001'
AND DateTime >= '2009-09-12 00:20'
AND DateTime <= '2009-09-12 00:40'
AND wwResolution = 10000
AND wwRetrievalMode = 'RoundTrip'
AND wwStateCalc = 'MaxContained'
If you run this query against the following sample data:

Tagname DateTime Resolution QualityDetail


I001 2009-09-12 00:12 1 90
I001 2009-09-12 00:15 2 65
I001 2009-09-12 00:22 1 85
I001 2009-09-12 00:23 2 75
I001 2009-09-12 00:26 1 75
I001 2009-09-12 00:29 2 70

The results are:

Tagname DateTime Value QualityD OPC-Quality StateTime


etail
I001 2009-09-12 00:20 NULL 65536 0 NULL
I001 2009-09-12 00:20 1.0 90 90 NULL
I001 2009-09-12 00:20 2.0 65 65 NULL
I001 2009-09-12 00:20 1.0 64 64 4000

116 Version 17.0.18000


Data Retrieval Options Wonderware Historian Retrieval Guide

Tagname DateTime Value QualityD OPC-Quality StateTime


etail
I001 2009-09-12 00:20 2.0 64 64 6000

Quality Rule - Query 7


The returned Quality Detail is the same as OP C quality unless there is special flag for certain
indication; for ex ample, when there is indication for rollover in counter mode.

SELECT TagName, DateTime, Value, QualityDetail, OPCQuality


FROM History
WHERE TagName = 'I0R5'
AND DateTime >= '2009-09-12 00:20'
AND DateTime <= '2009-09-12 00:40'
AND wwResolution = 10000
AND wwRetrievalMode = 'Avg'
If you run this query against the following sample data:

Tagname DateTime Resolution QualityDetail


I0R5 2009-09-12 00:07 2 218
I0R5 2009-09-12 00:14 3 218
I0R5 2009-09-12 00:22 0 218
I0R5 2009-09-12 00:25 1 218
I0R5 2009-09-12 00:27 0 218
I0R5 2009-09-12 00:29 2 218
I0R5 2009-09-12 00:33 3 218
I0R5 2009-09-12 00:36 0 218
I0R5 2009-09-12 00:39 1 218

The results are:

Tagname DateTime Value QualityDetail OPCQuality


I0R5 2009-09-12 00:20 2.6 218 218
I0R5 2009-09-12 00:30 1.0 218 218
I0R5 2009-09-12 00:40 1.6 218 218

Quality Rule - Query 8


For Interpolated mode only, the returned row with Linear wwInterpolationType will have combined
qualities.

SELECT TagName, DateTime, Value, QualityDetail, OPCQuality, wwRetrievalMode,


wwInterpolationType
FROM History
WHERE TagName = 'I0R5'
AND DateTime >= '2009-09-12 00:20'
AND DateTime <= '2009-09-12 00:40'

Version 17.0.18000 117


Wonderware Historian Retrieval Guide Data Retrieval Options

AND wwResolution = 10000


AND wwRetrievalMode = 'Interpolated'
AND wwInterpolationType = 'Linear'
If you run this query against the following sample data:

Tagname DateTime Resolution QualityDetail


I0R5 2009-09-12 00:07 2 193
I0R5 2009-09-12 00:14 3 195
I0R5 2009-09-12 00:22 0 196
I0R5 2009-09-12 00:25 1 199
I0R5 2009-09-12 00:27 0 200
I0R5 2009-09-12 00:29 2 207
I0R5 2009-09-12 00:33 3 215
I0R5 2009-09-12 00:36 0 216
I0R5 2009-09-12 00:39 1 219

The results are:

Tagname DateTime Value QualityDetail OPCQuality


I0R5 2009-09-12 00:20 0.8 192 192
I0R5 2009-09-12 00:30 2.3 192 192
I0R5 2009-09-12 00:40 1.0 192 219

Note: Cyclic, Full, Delta, Maximum, Minimum, and BestFit do not have combined qualities; therefore,
the rules are not applied to these modes..

State Calculation (wwStateCalc)

The state calculation setting applies to ValueState and RoundTrip retrieval.


For ValueState retrieval, you can choose the type of state calculation (aggregation) to be performed on
the data:
 Minimum: The shortest amount of time that the tag has been in eac h unique state.
 Maximum: The longest amount of time that the tag has been in each unique state.
 Average: The average amount of time that the tag has been in each unique state.
 Total: The total amount of time that the tag has been in each unique state.
 Percent: The total percent age of time that the tag has been in each unique state.
 MinContained: The shortest amount of time each tag has been in each unique state for each
cycle, disregarding the occurrences that are not fully contained with the calculation cycle.
 MaxContained: The longest amount of time that the tag has been in each unique state for each
cycle, disregarding the occurrences that are not fully contained with the calculation cycle.
 AvgContained: The average amount of time that the tag has been in each unique state for each
cycle, disregarding the occurrences that are not fully contained with the calculation cycle.

118 Version 17.0.18000


Data Retrieval Options Wonderware Historian Retrieval Guide

 TotalContained: The total amount of time that the tag has been in each unique state for each
cycle, disregarding the occurrences that are not fully contained with the calculation cycle.
 PercentContained: The percentage of time that the tag has been in eac h unique state for each
cycle, disregarding the occurrences that are not fully contained with the calculation cycle.
All results except Percent are in milliseconds. Percent is a percentage typically between 0.0 and 100.0.
The percent age can be higher than 100 in certain circumstances.
The nature of the data and how you set the cycle count determines whether you should use a
"contained" version of the aggregation. The calculations apply to each unique value state that the tag
was in during each retrieval cycle for the query. The total and percent calculations are alway s exact,
but the minimum, maximum, and average calculations are subject to "arbitrary" cycle boundaries that
do not coincide with the value changes. Therefore, non -intuitive results may be returned. This is most
apparent for slowly-changing tags queried over long cycles.
For example, a string tag that assumes only two distinct values changing every 10 minutes is queried
with a cycle time of two hours. Going into a cycle, the value (state) at the cycle boundary is recorded. If
the value then changes a short while into the cycle, the state found at the cycle start time will most
likely end up being the minimum value. Likewise, the state at the cycle end time is cut short at the
cycle end time. The two cut-off occurrences in turn skew the average calculation.
For RoundTrip retrieval, you can only specify the following types of state calculations (aggregations) to
be performed on the data. The calculations are for eac h unique state within each retrieval cycle for the
query.
 MinContained. The shortest time span between consecutive leading edges of any state that
occurs multiple times within the cycle, while disregarding state occurrences that are not fully
contained inside of the cycle.
 MaxContained. The longest time span bet ween consecutive leading edges of any s tate that
occurs multiple times within the cycle, while disregarding state occurrences that are not fully
contained inside of the cycle.
 AvgContained. The average time span between consecutive leading edges of any state that
occurs multiple times within the cycle, while disregarding state occurrences that are not fully
contained inside of the cycle. (This is the default.)
 TotalContained. The total time span bet ween consecutive leading edges of any state that occurs
multiple times within the cycle while disregarding state occurrences that are not fully contained
inside of the cycle.
 PercentContained. The percentage of the cycle time spent in time span between cons ecutive
leading edges for a state that occurs multiple times within the cycle while disregarding value
occurrences that are not fully contained inside of the cycle.

Analog Value Filtering (wwFilter)


You can use the following analog filters for all retrieval modes:
 Statistical removal of outliers
 Analog to discrete conversion
 Zero around a base value
These filt ers are applied in a query to retrieve data from the History table, WideHistory table, or
StateWideHistory table. These filter only apply to analog tags. All other types of tags, including analog
summary tags, are not supported.

Version 17.0.18000 119


Wonderware Historian Retrieval Guide Data Retrieval Options

You need to specify a filter name in the virt ual column wwFilter, with or without an override, to the set
of parameters that are defined for the specified filter. The filters are specified as C-like functions:
parentheses are always required, even when you choose not to override the default parameters by
passing no paramet ers.
The default value for the wwFilter column is ‘NoFilter’. If the query does not specify the wwFilt er
element at all, or if its default value is not overridden, then no filter is applied.
When you use the analog filters in a query that uses wwQualityRule, wwQualityRule is applied first and
wwFilter is applied later. You can only use one filter per query.

Statistically Removing Outliers (SigmaLimit)

This analog filter removes outliers from a set of analog points based on the assumption that the
distribution of point values in the set is a normal distribution.
The following illustration shows an example of outliers.

You can filter outliers by specifying a filter called ‘SigmaLimit()’. This filter has one parameter defined
for specifying the value of n. This parameter is of type double. If the paramet er is omitted, then a
default parameter of 2.0 is used.
When this filter is specified in any retrieval mode, a time weighted mean, ì (mu), and time weighted
standard deviation, ó (sigma), are found for each analog tag for the entire query range including
phantom cycles if any, and points falling outside of the range [ ì - nó, ì + nó] are removed from the point
set before the points are processed furt her. In other words, the value will be filtered out if valu e > ì + nó
or value < ì – nó.
Time weighted standard deviation is calculated as:
Math.Sqrt( (integralOfS quares - 2 * timeWeightedA verage * integral + totalTime *
timeWeightedA verage * timeWeightedA verage)/totalTime);
This is the single pass equivalent to the formula:

Ranges where the value is NULL are excluded from these calculations.
A cyclic query example using a ‘SigmaLimit()’ filter without specifying the n value would look like this:

SELECT DateTime, Value, wwFilter


FROM History

120 Version 17.0.18000


Data Retrieval Options Wonderware Historian Retrieval Guide

WHERE TagName = ('TankLevel')


AND DateTime >= '2008-01-15 15:00:00'
AND DateTime <= '2008-01-15 17:00:00'
AND wwRetrievalMode = 'Cyclic'
AND wwFilter = 'SigmaLimit()'
Not specifying the n-value as done here is the same as specifying ‘SigmaLimit(2)’. The result set might
look like this:

DateTime Value wwFilter


2008-01-15 15:00:00.000 34.56 SigmaLimit()
2008-01-15 16:00:00.000 78.90 SigmaLimit()
2008-01-15 17:00:00.000 12.34 SigmaLimit()

If the first value would be filtered out by the SigmaLimit filter, the value will be replaced with the time
weighted mean.

Converting Analog Values to Discrete Values (ToDiscrete)

The analog to discrete conversion filter allows you to convert value streams for any analog tag in the
query tag list into discrete value streams. The filter can be used with all the retrieval modes.
To convert analog values to discrete values, specify the ToDiscrete() filter in the wwFilter column. This
filter has two parameters:

Parameter Valid Values Default Value

CutoffValue any double value 0.0

Operator >, >=, or <= >

The following are supported syntaxes.


 ToDiscrete()
 ToDiscrete(2)
 ToDiscrete(2, >=)
The following are unsupported syntaxes.
 ToDiscrete(2, )
 ToDiscrete(, >=)
 ToDiscrete(>=)
The cutoff value holds the value that signifies the boundary bet ween values that are to be interpret ed
as OFF and values that are to be interpreted as ON.
The operator parameter controls the value range relative to the cutoff value to convert to the ON value
and vice versa.

Version 17.0.18000 121


Wonderware Historian Retrieval Guide Data Retrieval Options

NULLs encountered in the analog value stream are copied unchanged to the discrete value stream.
The quality of each discrete point is copied from the analog point that causes its production. However,
the quality detail for values modified wit h this filter will have the QualityDetail flag 0x2000 (value
changed by filter) set. For example, consider the following ValueState query:

SELECT DateTime, vValue, StateTime, wwFilter


FROM History
WHERE TagName IN ('SysTimeSec')
AND DateTime >= '2008-01-15 15:00:00'
AND DateTime <= '2008-01-15 17:00:00'
AND wwRetrievalMode = 'ValueState'
AND wwStateCalc = 'MinContained'
AND wwResolution = 7200000
AND wwFilter = 'ToDiscrete(29, >)'
Here the operator is specified as >, so values greater than but not including 29 are int ernally converted
to ON, whereas values from 0 to 29 are converted to OFF. This query could return the fol lowing rows:

DateTime vValue StateTime wwFilter


2008-01-15 15:00:00.000 0 30000 ToDiscrete(29, >)
2008-01-15 15:00:00.000 1 30000 ToDiscrete(29, >)
2008-01-15 17:00:00.000 0 30000 ToDiscrete(29, >)
2008-01-15 17:00:00.000 1 30000 ToDiscrete(29, >)

The values returned in the StateTime column show that the shortest amount of time that SysTimeSec
had values equivalent to either ON or OFF and remained in that state was 30 seconds. A similar
RoundTrip query would look like this:

SELECT DateTime, vValue, StateTime, wwFilter


FROM History
WHERE TagName IN ('SysTimeSec')
AND DateTime >= '2008-01-15 15:00:00'
AND DateTime <= '2008-01-15 17:00:00'
AND wwRetrievalMode = 'RoundTrip'
AND wwStateCalc = 'MaxContained'
AND wwResolution = 7200000
AND wwFilter = 'ToDiscrete(29, <=)'
Here the operator is specified as <=, so the resulting conversion is exactly opposite to that performed
in the previous query. Now values smaller than or equal to 29 are internally converted to ON, whereas
values from 30 to 59 are converted to OFF. This query could return the following rows:

DateTime vValue StateTime wwFilter


2008-01-15 15:00:00.000 0 60000 ToDiscrete(29, <=)
2008-01-15 15:00:00.000 1 60000 ToDiscrete(29, <=)
2008-01-15 17:00:00.000 0 60000 ToDiscrete(29, <=)
2008-01-15 17:00:00.000 1 60000 ToDiscrete(29, <=)

122 Version 17.0.18000


Data Retrieval Options Wonderware Historian Retrieval Guide

The values returned in the StateTime column now show that the longest amount of time found between
roundtrips for both the OFF and the ON state within the 2-hour cycles was 60 seconds.
Using the ToDiscret e() filter is similar to using edge detection for event tags. Edge detection
returns the actual value with a timestamp in history for when a value matched a certain criteria.
The ToDiscrete() filt er returns either a 1 or 0 to show that the criteria threshold was crossed. The
ToDiscrete() filter is more flexible, however, in the following ways:
 You can use it with delta and full retrieval.
 You can combine it with "time-in-state" calculations to determine how long a value is above a
certain threshold or the duration between threshold times.
Use the ToDiscrete() filt er if you are mostly interested in when something occurred, and not necessarily
the exact value of the event.
For more information on edge detection, see Edge Detection for Events (wwE dgeDetection) on page
78.

"Zeroing" Around a Base Value (SnapTo)

This analog filter lets you force values in a well -defined range around one or more base values to
"snap to" that base value. For example, you can use this filter when a tank is known to be empty, but
the tag that stores the tank level returns a "noisy" value close to zero.
The filter can be used with all retrieval modes, but its main benefits are in the aggregate ret rieval
modes: average, integral, minimum, and maximum.
To zero values around the base value, specify the SnapTo() filter in the wwFilter column of the query.
The syntax for this filter is:

SnapTo([tolerance[,base_value_1[, base_value_2]…]])
This filter has two parameters:

Parameter Valid Values Default Value

Tolerance any double value 0.01

BaseValue zero, one, or up to 100 comma-separated double single base value of 0.0
values

The following are supported syntaxes.


 SnapTo() – Same as SnapTo(0.01, 0.0)
 SnapTo(3.7) – Same as SnapTo(3.7, 0.0)
 SnapTo(3,) – Syntax Error
 SnapTo(,0) – Syntax error
 SnapTo(,) – Syntax error
 SnapTo(3, 4, -5) – Tolerance=3, Base Values 4 and -5.

Version 17.0.18000 123


Wonderware Historian Retrieval Guide Data Retrieval Options

When the Snap to filter is specified, point values falling inside any of the ranges [Base value –
Tolerance, Base value + Tolerance] will be forced to the base value before the point goes into further
retrieval proc essing. The result is undefined if the base value +/- tolerance exceeds the range of the
double data type. The range is calculated using this expression:

If (x <= Base value + Tolerance AND x >= Base value – Tolerance)


x = Base value
where x is the value of the point then if ranges overlap, the first matching base value will be used.
A query example from the History table looks like this:

SELECT DateTime, Value, wwFilter


FROM History
WHERE TagName = ('TankLevel')
AND DateTime >= '2008-01-15 15:00:00'
AND DateTime <= '2008-01-15 17:00:00'
AND wwRetrievalMode = 'Average'
AND wwResolution = 3600000
AND wwFilter = 'SnapTo(0.01, 0, 1000)'
The following rows might be returned:

DateTime Value wwFilter


2008-01-15 15:00:00.000 0 SnapTo(0.01, 0, 1000)
2008-01-15 16:00:00.000 875.66 SnapTo(0.01, 0, 1000)
2008-01-15 17:00:00.000 502.3 SnapTo(0.01, 0, 1000)

When a value is snapped, the QualityDetail bit flag 0x2000 is set.


If the filter syntax is not correct, a syntax error is returned and no rows are returned.

Selecting Values for Analog Summary Tags (wwValueSelector)


For an analog summary tag, multiple summarized values can be stored in the historian for a single
summarization period. When you query analog summary data, a single value, time, and quality (V TQ)
must first be extrapolated from the summarized values.
You set the value selector in the query to specify which summarized value to return. The possible
values are as follows:

Value Selector Setting Value Returned Timestamp Returned

AUTO The retrieval mode determines the The retrieval mode determines the
value. See the following table for how timestamp. See the following table
AUTO applies to the value selection. for how AUTO applies to the value
This is the default value. selection. This is the default value.

FIRS T The first value that occurs within the The actual timestamp of the first
summary period. value occurrenc e within the
summary period.

124 Version 17.0.18000


Data Retrieval Options Wonderware Historian Retrieval Guide

Value Selector Setting Value Returned Timestamp Returned

LAST The last value that occurs within the The actual timestamp of the last
summary period. value occurrenc e within the
summary period.

MIN or MINIMUM The first minimum value that occurs The actual timestamp of the first
within the summary period. minimum value occurrence within
the summary period.

MA X or MA XIMUM The first maximum value that occurs The actual timestamp of the first
within the summary period. maximum value occurrence wit hin
the summary period.

AVG or AVERAGE A time-weighted average calculated The summary period start time.
from values within the summary
period.

INTE GRA L An integral value calculated from The summary period start time.
values within the summary period.

STDDEV or A standard deviation calculated from The summary period start time.
STA NDA RDDEV IA TION values within the summary period.

The following table describes the value to be considered if the value selector is set to AUTO:

Retrieval Mode Analog Summary Behavior

Cyclic The last value within the summary period is used. The actual timestamp of the last
value occurrenc e within the summary period is used.

Delta The last value within the summary period is used. The actual timestamp of the last
value occurrenc e within the summary period is used.

Full The last value within the summary period is used. The actual timestamp of the last
value occurrenc e within the summary period is used.

Interpolated The retrieval mode determines the appropriate value to return. See the following
table for how A UTO applies to the value selection. This is the default value.

Best Fit The first, last, min, and max points from analog summaries are all considered as
analog input points. Best fit analysis is done with thes e points. If the analog
summary percentage good is not 100%, the cycle is considered to have a NULL.

Version 17.0.18000 125


Wonderware Historian Retrieval Guide Data Retrieval Options

Retrieval Mode Analog Summary Behavior

A verage The averages of analog summaries are calculated using the values from the
A verage column of the AnalogSummaryHistory table. Int erpolation type is ignored
for analog summary values, and S TAIRS TEP interpolation is always used.
PercentGood is calculated by considering the TimeGood of each analog summary.
If cycle boundaries do not exactly match the summary periods of the stored analog
summaries, the averages and time good are calculated by prorating the average
and time good values for the portion of the time the summary period overlaps with
the cycle. Quality will be set to 64 (uncertain) if cycle boundaries do not match
summary periods.
If the QualityDetail of any analog summary considered for a cycle is uncertain (64),
the resulting quality is set to 64.

Minimum The first minimum value within the summary period is used. The actual timestamp
of the first minimum value occurrence within the summary period is used.

Maximum The first maximum value within the summary period is used. The actual timestamp
of the first maximum value occurrence within the summary period is used.

Integral The integrals of analog summaries are calculated using the Integral column of the
AnalogSummaryHistory table. Interpolation type is ignored for analog summary
values, and S TA IRS TEP interpolation is always used. PercentGood is calculated by
considering the TimeGood of each analog summary.
If cycle boundaries do not exactly match the summary periods of the stored analog
summaries, the integrals and time good are calculated by prorating the integral and
time good values for the portion of the time the summary period overlaps with the
cycle. Quality is set to 64 (uncertain) if cycle boundaries do not match summary
periods.
If the QualityDetail of any analog summary considered for a cycle is uncertain (64),
the resulting quality will be set to 64.

Slope The last value within the summary period is used. The actual timestamp of the last
value occurrenc e within the summary period is used.

ValueState Cannot be used with analog summary dat a. No values are returned.

Counter Cannot be used with analog summary dat a. No values are returned.

RoundTrip Cannot be used with analog summary dat a. No values are returned.

For an analog summary tag, if any of the data within a summary period has an OP CQuality other than
Good, the OPCQuality returned will be Uncertain. This is true even for summary values that are not
calculated, such as first, last, minimum, maximum, and so on. For example, if the OPCQuality for a last
value is actually Good, but there was a I/O Server disconnect during the summary calculation period,
the OPCQuality for the last value is returned as Uncertain. A QualityDetail of 202 is used to distinguish
between the original point and the latest point.

126 Version 17.0.18000


Data Retrieval Options Wonderware Historian Retrieval Guide

Version 17.0.18000 127


Wonderware Historian Retrieval Guide

C HAPTER 3
SQL Query Examples
In addition to query examples that use the Wonderware Historian time domain extensions, other query
examples are provided to demonstrate how to perform more complex queries or to further explain how
retrieval works.
The examples provided are not exhaustive of all possible dat abas e queries, but they should give you
an idea of the kinds of queries that you could write.
For general information on creating SQL queries, see your Microsoft SQL Server documentation.

Note: If you have configured SQL Server to be case-sensitive, be sure that you use the correct case
when writing queries.

Version 17.0.18000 129


Wonderware Historian Retrieval Guide SQL Query Examples

In This Chapter
Querying the History Table .......................................................................................................... 131
Querying the Live Table .............................................................................................................. 131
Querying the WideHistory Table .................................................................................................. 132
Querying Wide Tables in Delta Retrieval Mode ............................................................................. 133
Querying the AnalogSummaryHistory View .................................................................................. 134
Querying the StateS ummaryHistory View ..................................................................................... 134
Using an Unconventional Tagname in a Wide Table Query ........................................................... 135
Using an INNE R REMOTE JOIN ................................................................................................. 136
Setting Both a Time and Value Deadband for Retrieval ................................................................. 136
Using wwResolution, wwCycleCount, and ww Ret rievalMode in the Same Query ............................ 139
Determining Cycle Boundaries..................................................................................................... 139
Mixing Tag Types in the Same Query........................................................................................... 140
Using a Criteria Condition on a Column of Variant Data ................................................................. 141
Using DateTime Functions .......................................................................................................... 141
Using the GROUP BY Clause...................................................................................................... 143
Using the COUNT() Function ....................................................................................................... 143
Using an Arithmetic Function ....................................................................................................... 144
Using an Aggregate Function ...................................................................................................... 144
Making and Querying Annotations ............................................................................................... 146
Using Comparison Operators with Delta Retrieval ......................................................................... 146
Using Comparison Operators with Cyclic Retrieval and Cycle Count .............................................. 151
Using Comparison Operators with Cyclic Retrieval and Resolution ................................................. 154
Returning Time Bet ween Value Changes ..................................................................................... 157
SELECT INTO from a History Table ............................................................................................. 162
Moving Data from a SQL Server Table to an Extension Table ........................................................ 163
Using Server-Side Curs ors .......................................................................................................... 164
Using Stored Procedures in OLE DB Queries ............................................................................... 165
Getting Data from the OPCQualityMap Table ............................................................................... 165
Using Variables with the Wide Table ............................................................................................ 166
Retrieval Across a Data Gap in Classically Stored Data ................................................................ 166
Returned Values for Non-V alid Start Times .................................................................................. 168
Querying Aggregate Data in Different Ways ................................................................................. 168
Bitwise Retrieval for Process Data ............................................................................................... 170

130 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

Querying the History Table


The History table presents acquired plant data in a historical format. For more information, see History
Tables in the Wonderware Historian Database Reference.
The following query returns the date/time stamp and value for the tag "ReactLevel." The query uses
the remote table view (History is used in place of INSQL.Runtime.dbo.History).
If you do not specify a wwCycleCount or wwResolution, the query will return 100 rows (the default).

SELECT DateTime, Sec = DATEPART(ss, DateTime), TagName, Value


FROM History
WHERE TagName = 'ReactLevel'
AND DateTime >= '2001-03-13 1:15:00pm'
AND DateTime <= '2001-03-13 2:15:00pm'
AND wwRetrievalMode = 'Cyclic'

The results are:

DateTime Sec TagName Value


2001-03-13 13:15:00.000 0 ReactLevel 1775.0
2001-03-13 13:15:00.000 36 ReactLevel 1260.0
2001-03-13 13:16:00.000 12 ReactLevel 1650.0
2001-03-13 13:16:00.000 49 ReactLevel 1280.0
2001-03-13 13:17:00.000 25 ReactLevel 1525.0
2001-03-13 13:18:00.000 1 ReactLevel 585.0
2001-03-13 13:18:00.000 38 ReactLevel 1400.0
2001-03-13 13:19:00.000 14 ReactLevel 650.0
2001-03-13 13:19:00.000 50 ReactLevel 2025.0
2001-03-13 13:20:00.000 27 ReactLevel 765.0
2001-03-13 13:21:00.000 3 ReactLevel 2000.0
2001-03-13 13:21:00.000 39 ReactLevel 830.0
2001-03-13 13:22:00.000 16 ReactLevel 1925.0
...

(100 row(s) affected)

Querying the Live Table


The Live table presents the latest available streamed data for each tag in the table.

Note: In certain situations, data can by pass the Live table. These situations include:
- Receiving non-streamed original data (store/forward or CSV);
- Receiving revision data for a Latest value;
- Receiving no new streamed values after Historian was shut down and disabled, or after the
computer was rebooted.

For more information, see History Tables in the Wonderware Historian Dat abase Reference.
Version 17.0.18000 131
Wonderware Historian Retrieval Guide SQL Query Examples

The following query returns the current value of the specified tag. The query uses the remote table
view (Live is used in place of INSQL.Runtime.dbo.Live).

SELECT TagName, Value


FROM Live
WHERE TagName = 'ReactLevel'

The result is:

TagName Value
ReactLevel 1145.0
(1 row(s) affected)

Querying the WideHistory Table

The wide extension table is a transposition of the History table. Use the wide history tables any time
you want to find the value of one or more tags over time and need to specify different filter criteria for
each tag.
For more information, see History Tables in the Wonderware Historian Dat abase Reference.
The following query returns the value of two tags from the WideHistory table. The WideHistory table
can only be accessed using the OPE NQUERY function. The "Runtime.dbo." qualifier is optional.

SELECT * FROM OpenQuery(INSQL,'


SELECT DateTime, ReactLevel, ReactTemp
FROM Runtime.dbo.WideHistory
WHERE Reactlevel > 1500
AND ReactTemp > 150
')

The results are:

DateTime ReactLevel ReactTemp


2001-03-02 06:20:00.000 1865.0 191.3
2001-03-02 06:21:00.000 2025.0 195.9
2001-03-02 06:22:00.000 2000.0 195.9
2001-03-02 06:23:00.000 2025.0 180.9
2001-03-02 06:27:00.000 1505.0 177.5
(5 row(s) affected).

In the WideHistory table, the column type is determined by the tag type.

SELECT * FROM OpenQuery(INSQL, 'SELECT DateTime, SysTimeMin, SysPulse, SysString


FROM WideHistory
WHERE DateTime >= "2001-12-20 0:00"
AND DateTime <= "2001-12-20 0:05"
AND wwRetrievalMode = "delta"
')

132 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

The results are:

DateTime SysTime SysPulse SysString


Min
2001-12-20 00:00:00.000 0 0 2001/12/20 08:00:00
2001-12-20 00:01:00.000 1 1 2001/12/20 08:00:00
2001-12-20 00:02:00.000 2 0 2001/12/20 08:00:00
2001-12-20 00:03:00.000 3 1 2001/12/20 08:00:00
2001-12-20 00:04:00.000 4 0 2001/12/20 08:00:00
2001-12-20 00:05:00.000 5 1 2001/12/20 08:00:00

Querying Wide Tables in Delta Retrieval Mode


Wide tables in delta retrieval mode will behave normally if only one tag is returned. However, for a
multiple tag display, a complete row is returned to the client for each instance in which one or more of
the tags in the query ret urns a different value. The row will reflect the actual values being returned for
the tags returning results, and will reflect the previous values for the remaining tags in the result set
(similar to cyclic retrieval).

Note: The value can be "invalid" or some other quality value.

The following query returns values for three tags from the WideHistory table. "MyTagName" is a tag
that periodically is invalid.

SELECT * FROM OpenQuery(INSQL,'


SELECT DateTime, SysTimeSec, SysTimeMin, MyTagName
FROM WideHistory
WHERE DateTime >= "2001-05-12 13:00:00"
AND DateTime <= "2001-05-12 13:02:00"
AND wwRetrievalMode = "Delta"
')
The results are:

DateTime SysTimeSec SysTimeMin MyTagName


...

2001-05-12 13:00:55.000 55 00 1
2001-05-12 13:00:56.000 56 00 1
2001-05-12 13:00:57.000 57 00 1
2001-05-12 13:00:57.500 57 00 null
2001-05-12 13:00:58.000 58 00 null
2001-05-12 13:00:59.000 59 00 null
2001-05-12 13:01:00.000 00 01 null
2001-05-12 13:01:00.500 00 01 2
2001-05-12 13:01:01.000 01 01 2
2001-05-12 13:01:02.000 02 01 2

Version 17.0.18000 133


Wonderware Historian Retrieval Guide SQL Query Examples

2001-05-12 13:01:03.000 03 01 2
...

Notice that 57 appears twice since the occurrence of 1 changing to NULL for tag "MyTagName" occurs
sometime bet ween the 57th and 58t h second. The same applies for NULL changing to 2. The same
behavior applies to discrete values.

Querying the AnalogSummaryHistory View


The AnalogS ummaryHistory view is a "wide" view that allows you to return multiple statistics for a
single tag wit hin a single query.
The following query returns the minimum, maximum, and average values for the SysTimeSec tag for
the last hour.

declare @End datetime


set @End = left(convert(varchar(30),getdate(),120),14)+'00:00'
SELECT Tagname, OPCQuality, Minimum as MIN, Maximum as MAX, Average as AVG
FROM AnalogSummaryHistory
WHERE TagName = 'SysTimeSec'
AND StartDateTime >= dateadd(minute,-60,@End)
AND EndDateTime < @End
AND wwCycleCount = 2

The results are:

Tagname OPCQuality MIN MAX AVG


SysTimeSec 192 0 59 29.5

Querying the StateSummaryHistory View


The StateSummary History view is a "wide" view that allows you to return multiple statistics for a single
tag within a single query.
The following query returns the state count, total time in state, and the percentage of time in state for
the SysPulse system tag for the last hour. One row is returned for each state.

DECLARE @End DateTime


SET @END = getdate()
SELECT
TagName,
Value,
OPCQuality,
StateCount,
StateTimeTotal,
StateTimePercent
FROM dbo.StateSummaryHistory
WHERE TagName = N'SysPulse'
AND StartDateTime >= dateadd(minute,-60,@End)
AND EndDateTime <= @End
AND wwCycleCount = 1
The results are:

TagName Value OPCQuality State StateTimeTotal StateTimePercent

134 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

Count
SysPulse 1 192 30 1800000 50

SysPulse 0 192 30 1800000 50

The following query returns the minimum time in state, the minimum contained time in state, and value
for the SysTimeS ec system tag.

SELECT
TagName,
StartDateTime,
EndDateTime,
StateTimeMin as STM,
StateTimeMinContained as STMC,
Value
FROM StateSummaryHistory
WHERE TagName='SysTimeSec'
AND wwRetrievalMode='Cyclic'
AND wwResolution=5000
AND StartDateTime>='2009-10-21 17:40:00.123'
AND StartDateTime<='2009-10-21 17:40:05.000'
The results are:

TagName StartDateTime EndDateTime STM STMC Value


SysTimeSec 2009-10-21 2009-10-21 877 0 0
17:40:00.123 17:40:05.123
SysTimeSec 2009-10-21 2009-10-21 1000 1000 1
17:40:00.123 17:40:05.123
SysTimeSec 2009-10-21 2009-10-21 1000 1000 2
17:40:00.123 17:40:05.123
SysTimeSec 2009-10-21 2009-10-21 1000 1000 3
17:40:00.123 17:40:05.123
SysTimeSec 2009-10-21 2009-10-21 1000 1000 4
17:40:00.123 17:40:05.123
SysTimeSec 2009-10-21 2009-10-21 123 0 5
17:40:00.123 17:40:05.123

Using an Unconventional Tagname in a Wide Table Query

In a SQL query against a wide table, unconventional tag names must be delimited with brackets ( [ ] ),
because the tagname is used as a column name. For example, tagnames containing a minus ( - ) or a
forward slash ( / ) must be delimited, otherwise the parser will attempt to perform the corresponding
arithmetic operation. No error will result from using brackets where not strictly necessary. For more
information on unconventional tagnames, see Tag Naming Conventions.
The following is an example of how to delimit a tagname i n a query on a wide table. "ReactTemp -2"
and "React Temp+2" are tagnames. Without the delimiters, the pars er would attempt to include the " -2"
and "+2" suffixes on the tagnames as part of the arithmetic operation.

Version 17.0.18000 135


Wonderware Historian Retrieval Guide SQL Query Examples

For clarity and maintainability of your que ries, however, it is recommended that you do not use special
characters in tagnames unless strictly necessary.

SELECT * FROM OpenQuery(INSQL,


'SELECT ReactTemp, [ReactTemp-2]-2, [ReactTemp+2]+2 FROM WideHistory WHERE
... ')

Using an INNER REMOTE JOIN

Instead of using " … WHERE TagName IN (SELECT TagName … ) ", it is more efficient to use INNER
REMOTE JOIN syntax.
In general, use the following pattern for INNE R REMOTE JOIN queries against the historian:
<SQLServerTable> INNER REMOTE JOIN <HistorianExtensionTable>
This query returns data from the history table, based on a string tag that you filter for from the
StringTag table:

SELECT DateTime, T.TagName, vValue, Quality, QualityDetail


FROM StringTag T inner remote join History H
ON T.TagName = H.TagName
WHERE T.MaxLength = 64
AND DateTime >='2002-03-10 12:00:00.000'
AND DateTime <='2002-03-10 16:40:00.000'
AND wwRetrievalMode = 'Delta'

This query returns data from the history table, based on a discrete tag that you filter for from the Tag
table:

SELECT DateTime, T.TagName, vValue, Quality, QualityDetail


FROM Tag T inner remote join History H
ON T.TagName = H.TagName
WHERE T.TagType = 2
AND T.Description like 'Discrete%'
AND DateTime >='2002-03-10 12:00:00.000'
AND DateTime <='2002-03-10 16:40:00.000'
AND wwRetrievalMode = 'Delta'

Setting Both a Time and Value Deadband for Retrieval


If both time and value deadbands are specified, then every sample is checked for both deadbands,
against the current basis value (the last sample returned).
If it passes both tests, then it is returned and acts as the basis for checking the next sample.
For example:

SELECT DateTime, TagName, Value


FROM History
WHERE TagName = 'ReactTemp'
AND DateTime >= '2002-03-13 10:08'
AND DateTime <= '2002-03-13 10:28'
AND wwRetrievalMode = 'Delta'
AND wwTimeDeadband = 5000
AND wwValueDeadband = 5

136 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

The tag selected, 'React Temp,' has a MinE U value of 0 and a MaxEU value of 220. Thus, the value
deadband will be 5 percent of (220 - 0), which equals 11. React Temp changes rapidly between its
extreme values, but the value remains constant for short periods near the high and low temperature
limits. Therefore, when changes are rapid, the value deadband condition is satisfied first, then the time
deadband is satisfied. In this region, the behavior is dominated by the time deadband, and the returned
rows are spaced at 5 second intervals. Where the temperature is more constant (particularly at the low
temperature end), the time deadband is satisfied first, followed by the value deadband. Both
deadbands are only satisfied when the value of a row is more than 11 degrees different from the
previous row. Thus, the effect of value deadband can be seen to dominate near the low and high
temperature extremes of the tag.
The results are:

DateTime TagName Value


2002-03-13 10:08:00.000 ReactTemp 121.0
2002-03-13 10:08:10.000 ReactTemp 189.10000610351562
2002-03-13 10:08:20.000 ReactTemp 147.69999694824219
2002-03-13 10:08:30.000 ReactTemp 106.30000305175781
2002-03-13 10:08:40.000 ReactTemp 30.100000381469727
2002-03-13 10:08:50.000 ReactTemp 16.399999618530273
2002-03-13 10:09:00.000 ReactTemp 61.0
2002-03-13 10:09:10.000 ReactTemp 151.0
2002-03-13 10:09:20.000 ReactTemp 173.0
2002-03-13 10:09:30.000 ReactTemp 131.60000610351562
2002-03-13 10:09:40.000 ReactTemp 57.700000762939453
2002-03-13 10:09:50.000 ReactTemp 16.299999237060547
2002-03-13 10:10:10.000 ReactTemp 96.0
2002-03-13 10:10:20.000 ReactTemp 186.0
2002-03-13 10:10:30.000 ReactTemp 156.89999389648437
2002-03-13 10:10:40.000 ReactTemp 115.5
2002-03-13 10:10:50.000 ReactTemp 41.599998474121094
2002-03-13 10:11:00.000 ReactTemp 21.0
2002-03-13 10:11:10.000 ReactTemp 41.0
2002-03-13 10:11:20.000 ReactTemp 131.0
2002-03-13 10:11:30.000 ReactTemp 184.5
2002-03-13 10:11:40.000 ReactTemp 140.80000305175781
2002-03-13 10:11:50.000 ReactTemp 99.400001525878906
2002-03-13 10:12:00.000 ReactTemp 25.5
2002-03-13 10:12:20.000 ReactTemp 76.0
2002-03-13 10:12:30.000 ReactTemp 166.0
2002-03-13 10:12:50.000 ReactTemp 124.69999694824219

Version 17.0.18000 137


Wonderware Historian Retrieval Guide SQL Query Examples

DateTime TagName Value


2002-03-13 10:13:00.000 ReactTemp 50.799999237060547
2002-03-13 10:13:10.000 ReactTemp 16.399999618530273
2002-03-13 10:13:30.000 ReactTemp 111.0
2002-03-13 10:13:40.000 ReactTemp 193.69999694824219
2002-03-13 10:13:50.000 ReactTemp 152.30000305175781
2002-03-13 10:14:00.000 ReactTemp 108.59999847412109
2002-03-13 10:14:10.000 ReactTemp 34.700000762939453
2002-03-13 10:14:20.000 ReactTemp 21.0
2002-03-13 10:14:30.000 ReactTemp 51.0
2002-03-13 10:14:40.000 ReactTemp 146.0
2002-03-13 10:14:50.000 ReactTemp 177.60000610351562
2002-03-13 10:15:00.000 ReactTemp 136.19999694824219
2002-03-13 10:15:10.000 ReactTemp 92.5
2002-03-13 10:15:20.000 ReactTemp 18.600000381469727
2002-03-13 10:15:40.000 ReactTemp 86.0
2002-03-13 10:15:50.000 ReactTemp 181.0
2002-03-13 10:16:00.000 ReactTemp 161.5
2002-03-13 10:16:10.000 ReactTemp 120.09999847412109
2002-03-13 10:16:20.000 ReactTemp 76.400001525878906
2002-03-13 10:16:30.000 ReactTemp 20.899999618530273
2002-03-13 10:16:50.000 ReactTemp 81.0
2002-03-13 10:17:00.000 ReactTemp 176.0
2002-03-13 10:17:10.000 ReactTemp 163.80000305175781
2002-03-13 10:17:20.000 ReactTemp 122.40000152587891
2002-03-13 10:17:30.000 ReactTemp 46.200000762939453
2002-03-13 10:17:40.000 ReactTemp 18.700000762939453
2002-03-13 10:18:00.000 ReactTemp 116.0
2002-03-13 10:18:10.000 ReactTemp 189.10000610351562
2002-03-13 10:18:20.000 ReactTemp 147.69999694824219
...

138 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

Using wwResolution, wwCycleCount, and wwRetrievalMode


in the Same Query
The results of a dat abas e query will vary depending on the combination of resolution, cycle count, and
retrieval mode that you use in the query. These results are summarized in the following table (where N
is a numeric value):

Retrieval
Mode Resolution Cycle Count Results

CYCLIC N 0 (or no All stored data for tags during the specified time
value) interval are queried, and then a resolution of N ms
applied.

CYCLIC 0 (or no value) 0 The server will return 100,000 rows per tag specified.

CYCLIC 0 (or no value) N All stored data for tags during the specified time
interval are queried, and then a cycle count of N evenly
spaced rows is applied.

CYCLIC N (any value is All stored data for tags during the specified time
ignored) interval are queried, and then a resolution of N ms
applied.

CYCLIC (no value) (no value or a The server will return 100 rows per tag specified.
value less
than 0)

DELTA (any value is 0 All values that changed during the specified time
ignored) interval are returned (up to 100,000 rows total).

DELTA (any value is N Values that changed during the specified time interval
ignored) are queried, and then a cycle count (first N rows) is
applied. The cycle count limits the maximum number of
rows returned, regardless of how many tags were
queried. For example, a query that applies a cycle
count of 20 to four tags will return a maximum of 20
rows of data. An initial row will be returned for each
tag, and the remaining 16 rows will be bas ed on
subsequent value changes for any tag.

DELTA (any value is (no value) All values that changed during the specified time
ignored) interval are returned (no row limit).

In general, if there is an error in the virt ual columns, or an unresolvable conflict, then zero rows are
returned.

Determining Cycle Boundaries

Version 17.0.18000 139


Wonderware Historian Retrieval Guide SQL Query Examples

Cycle boundaries are calculated based on the query start and end times, wwCycleCount, and
wwResolution.
If you only specify wwCycleCount, evenly spaced cycles are returned based on the value of
wwCycleCount.
If you only specify wwResolution, cycles are spaced wwResolution milliseconds apart starting at the
query start time until query end time is reached. The last cycle will have whatever duration is required
to end exactly at the query end time. If this last duration is shortened by this rule, it is known as a
partial cycle. Because of this, the final cycle duration may not match wwRes olution.
If both wwCycleCount and wwResolution are specified, no result rows will be returned. If you specify
neither wwCycleCount nor wwResolution in the query, the query will return 100 rows.
Unless otherwise specified, a value is considered in a given full or partial cycle if its timestamp occurs
at or after the cycle start (timestamp >= cycle start) and before the cycle end (t imestamp < cycle end).

Mixing Tag Types in the Same Query


The History and Live tables use the sql_variant data type for the vValue column, allowing the return of
various data types in a single column. In ot her words, these tables allow valu es for tags of different
types to be retrieved with a simple query, without the need for a JOIN operation.
For example:

SELECT TagName, DateTime, vValue


FROM History
WHERE TagName IN ('SysTimeMin', 'SysPulse', 'SysString')
AND DateTime >= '2001-12-20 0:00'
AND DateTime <= '2001-12-20 0:05'
AND wwRetrievalMode = 'delta'

The results are:

TagName DateTime vValue


SysTimeMin 2001-12-20 00:00:00.000 0
SysPulse 2001-12-20 00:00:00.000 0
SysString 2001-12-20 00:00:00.000 2001/12/20 08:00:00
SysTimeMin 2001-12-20 00:01:00.000 1
SysPulse 2001-12-20 00:01:00.000 1
SysTimeMin 2001-12-20 00:02:00.000 2
SysPulse 2001-12-20 00:02:00.000 0
SysTimeMin 2001-12-20 00:03:00.000 3
SysPulse 2001-12-20 00:03:00.000 1
SysTimeMin 2001-12-20 00:04:00.000 4
SysPulse 2001-12-20 00:04:00.000 0
SysTimeMin 2001-12-20 00:05:00.000 5
SysPulse 2001-12-20 00:05:00.000 1

140 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

Using a Criteria Condition on a Column of Variant Data


The Wonderware Historian OLE DB provider sends variant data to the SQL Server as a string. If the
query contains a criteria condition on a column containing variant type data, the filtering is handled by
SQL Server. An example of a criteria condition is:

WHERE ... vValue = 2


To perform the filtering, the SQL Server must determine the data type of the constant (in this example,
2), and attempt to convert the variant (string) to this destination type. The SQL Server assumes that a
constant without a decimal is an integer, and attempts to convert the string to an int eger type. This
conversion will fail in SQL Server if the string actually represents a float (for ex ample, 2.00123 ).
You should explicitly state the destination type by means of a CONVERT function. This is the only
reliable way of filtering on the vValue column, which contains variant data.
For example:

SELECT DateTime, Quality, OPCQuality, QualityDetail, Value, vValue, TagName


FROM History
WHERE TagName IN ('ADxxxF36', 'SysTimeMin', 'SysPulse')
AND DateTime >= '12-04-2001 04:00:00.000'
AND DateTime <= '12-04-2001 04:03:00.000'
AND wwRetrievalMode = 'Delta'
AND convert(float, vValue) = 2
The following is another example:

SELECT DateTime, Quality, OPCQuality, QualityDetail, Value, vValue, TagName


FROM History
WHERE TagName IN ('VectorX', 'SysTimeMin', 'SysPulse')
AND DateTime >= '20020313 04:00:07.000'
AND DateTime <= '20020313 04:01:00.000'
AND wwRetrievalMode = 'Delta'
AND convert(float, vValue) > 1
AND convert(float, vValue) < 2

Using DateTime Functions


Date functions perform an operation on a date and time input value and return eithe r a string, numeric,
or dat e and time value.
The following query returns the date/time stamp and value for the SysTimeS ec tag for the last 10
minutes.

SELECT DateTime, TagName, Value, Quality


FROM History
WHERE TagName = 'SysTimeSec'
AND DateTime >= dateadd(Minute, -10, GetDate())
AND DateTime <= GetDate()
AND wwRetrievalMode = 'Cyclic'

The results are:

DateTime TagName Value Quality


2001-12-15 13:00:00.000 SysTimeSec 0.0 0
2001-12-15 13:00:06.060 SysTimeSec 6.0 0

Version 17.0.18000 141


Wonderware Historian Retrieval Guide SQL Query Examples

2001-12-15 13:00:12.120 SysTimeSec 12.0 0


2001-12-15 13:00:18.180 SysTimeSec 18.0 0
2001-12-15 13:00:24.240 SysTimeSec 24.0 0
2001-12-15 13:00:30.300 SysTimeSec 30.0 0
2001-12-15 13:00:36.360 SysTimeSec 36.0 0
2001-12-15 13:00:42.420 SysTimeSec 42.0 0
...

If you want to use date/time functions and the wwTimeZone paramet er in the same query, you will
need to use the faaTZgetdate() function. This is because of differences in how the SQL Server and the
Wonderware Historian OLE DB provider determine the end date for a query.
For any query, the SQL Server performs all date/time computations in local server time, reformulates
the query with specific dates, and sends it on to the Wonderware Historian OLE DB provider. The
Wonderware Historian OLE DB provider then applies the wwTimeZone parameter in determining the
result set.
For example, the following query requests the last 30 minutes of data, expr essed in Eastern Daylight
Time (EDT). The server is located in the P acific Daylight Time (PDT) zone.

SELECT DateTime, TagName, Value FROM History


WHERE TagName IN ('SysTimeHour', 'SysTimeMin', 'SysTimeSec')
AND DateTime > DateAdd(mi, -30, GetDate())
AND wwTimeZone = 'eastern daylight time'

If it is currently 14:00:00 in the Pacific Daylight Time zone, then it is 17:00:00 in the Eastern Daylight
Time zone. You would expect the query to return data from 16:30:00 to 17:00:00 EDT, representing the
last 30 minutes in the Eastern Daylight Time zone.
However, the data that is returned is from 13:30:00 to 17:00:00 EDT. This is because the SQL Server
computes the "DateAdd(mi, -30, GetDate())" part of the query assuming the local server time
zone (in this example, PDT). It then passes the Wonderware Historian OLE DB provider a query similar
to the following:

SELECT DateTime, TagName, Value FROM History


WHERE TagName IN ('SysTimeHour', 'SysTimeMin', 'SysTimeSec')
AND DateTime > 'YYYY-MM-DD 13:30:00.000'
AND wwTimeZone = 'eastern daylight time'

Because the OLE DB provider is not provided an end date, it assumes the end date to be the current
time in the specified time zone, which is 17:00: 00 EDT.
To work around this problem, use the faaTZgetdate() function with intermediate variables. For
example:

DECLARE @starttime datetime


SET @starttime = dbo.faaTZgetdate('eastern daylight time')
SELECT DateTime, TagName, Value FROM History
WHERE TagName IN ('SysTimeHour', 'SysTimeMin', 'SysTimeSec')
AND DateTime > DateAdd(mi, -30, @starttime)
AND DateTime < DateAdd(mi, -5, @starttime)
AND wwTimeZone = 'eastern daylight time'

142 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

The following example uses a wide table:

SELECT * FROM OpenQuery(INSQL, '


SELECT DateTime, SysTimeHour, SysTimeMin, SysTimeSec FROM WideHistory
WHERE DateTime > DateAdd(mi, -30, faaTZgetdate("eastern daylight time"))
AND DateTime < DateAdd(mi, -5, faaTZgetdate("eastern daylight time"))
AND wwTimeZone = "eastern daylight time"
')

Using the GROUP BY Clause


The GROUP BY clause works if the query uses the four -part naming convention or one of the
associated views.
The following example will find the highest value of a specified set of tags over a time period.

SELECT TagName, Max(Value)


FROM INSQL.Runtime.dbo.History
WHERE TagName IN ('ReactTemp','ReactLevel','SysTimeSec')
AND DateTime > '2001-12-20 0:00'
AND DateTime < '2001-12-20 0:05'
GROUP BY TagName
The results are:

SysTimeSec 59.0

Using the COUNT() Function


The COUNT(*) function works directly in a four-part query, but is not supported inside of the
OPENQUERY function.
For example:

SELECT count(*)
FROM History
WHERE TagName = 'SysTimeSec'
AND DateTime >= '2001-12-20 0:00'
AND DateTime <= '2001-12-20 0:05'
AND wwRetrievalMode = 'delta'
AND Value >= 30

The result is:

150

If you use the OPE NQUERY function, you cannot perform arithmetic functions on the COUNT(*)
column. However, you can perform the count outside of the OPE NQUERY, as follows:

SELECT count(*), count(*)/2 FROM OPENQUERY(INSQL, 'SELECT DateTime, vValue,


Quality, QualityDetail
FROM History
WHERE TagName IN ("SysTimeSec")
AND DateTime >= "2002-04-16 03:00:00.000"
AND DateTime <= "2002-04-16 06:00:00.000"
AND wwRetrievalMode = "Delta"

Version 17.0.18000 143


Wonderware Historian Retrieval Guide SQL Query Examples

')

The result is:

10801 5400
(1 row(s) affected)

Using an Arithmetic Function


The following query adds the values of two tags from the WideHistory table.

SELECT * FROM OpenQuery(INSQL,'


SELECT DateTime, ReactLevel, ProdLevel, "Sum" = ReactLevel+Prodlevel
FROM WideHistory
WHERE DateTime > "2001-02-28 18:56"
AND DateTime < "2001-02-28 19:00"
AND wwRetrievalMode = "Cyclic"
')

The results are:

DateTime ReactLevel Prodlevel Sum


2001-02-28 18:56:00.000 1525.0 2343.0 3868.0
2001-02-28 18:56:00.000 1525.0 2343.0 3868.0
2001-02-28 18:56:00.000 1525.0 2343.0 3868.0
2001-02-28 18:56:00.000 1525.0 2343.0 3868.0
2001-02-28 18:56:00.000 2025.0 2343.0 4368.0
2001-02-28 18:56:00.000 2025.0 2343.0 4368.0
...

(100 row(s) affected)

If you use a math operator, such as plus (+), minus (-), multiply (*), or divide (/), you will need to add a
blank space in front of and after the operator. For example, "Value - 2" instead of "Value-2".

Using an Aggregate Function


The following query returns the minimum, maximum, average, and sum of the tag 'ReactLevel' from the
WideHistory table.

SELECT * FROM OpenQuery(INSQL,'


SELECT "Minimum" = min(ReactLevel),
"Maximum" = max(ReactLevel),
"Average" = avg(ReactLevel),
"Sum" = sum(ReactLevel)
FROM WideHistory
WHERE DateTime > "2001-02-28 18:55:00 "
AND DateTime < "2001-02-28 19:00:00"
AND wwRetrievalMode = "Cyclic"
')

144 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

The results are:

Minimum Maximum Average Sum


-25.0 2025.0 1181.2 118120.0
(1 row(s) affected)
If you perform a S UM or AVG in delta retrieval mode against the Wide table, the aggregation will only
be performed when the value has changed. The aggregation will not apply to all of the rows returned
for each column.
For example, the following query has no aggregation applied:

SELECT * FROM OpenQuery(INSQL, 'SELECT DateTime, SysTimeHour, SysTimeMin,


SysTimeSec, SysDateDay
FROM AnalogWideHistory
WHERE DateTime >= "2001-08-15 13:20:57.345"
AND DateTime < "2001-08-15 13:21:03.345"
AND wwRetrievalMode = "Delta"
')
GO

The results are:

DateTime SysTimeHour SysTimeMin SysTimeSec SysDateDay


2001-08-15 13:20:57.343 13 20 57 15
2001-08-15 13:20:58.000 13 20 58 15
2001-08-15 13:20:59.000 13 20 59 15
2001-08-15 13:21:00.000 13 21 0 15
2001-08-15 13:21:01.000 13 21 1 15
2001-08-15 13:21:02.000 13 21 2 15
2001-08-15 13:21:03.000 13 21 3 15
(7 row(s) affected)

Then, a SUM is applied to all of the returned column values:

SELECT * FROM OpenQuery(INSQL,'SELECT Sum(SysTimeHour), Sum(SysTimeMin),


Sum(SysTimeSec), Sum(SysDateDay)
FROM WideHistory
WHERE DateTime >= "2001-08-15 13:20:57.345"
AND DateTime < "2001-08-15 13:21:03.345"
AND wwRetrievalMode = "Delta"
')
GO

The results are:

SysTimeHour SysTimeMin SysTimeSec SysDateDay


13 41 180 15

Version 17.0.18000 145


Wonderware Historian Retrieval Guide SQL Query Examples

Thus, for delta retrieval mode, a S UM or AVG is applied only if the value has changed from the
previous row.
If you perform an AVG in delta retrieval mode, AVG will be computed as:
SUM of delta values/number of delta values
For example, an AVG is applied to all of the returned column values:

SELECT * FROM OpenQuery(INSQL,'SELECT Avg(SysTimeHour), Avg(SysTimeMin),


Avg(SysTimeSec), Avg(SysDateDay)
FROM WideHistory
WHERE DateTime >= "2001-08-15 13:20:57.345"
AND DateTime < "2001-08-15 13:21:03.345"
AND wwRetrievalMode = "Delta"
')
GO

The results are:

SysTimeMin SysTimeSec
20.5 25.714285714285715

Making and Querying Annotations


The following query creates an annotation for the specified tag. The annotation is made in response to
a pump turning off. Then, the annotations for a particular tag are returned.

DECLARE @@UserKey INT


SELECT @@UserKey = UserKey
FROM UserDetail
WHERE UserName = 'wwAdmin'
INSERT INTO Annotation (TagName, UserKey, DateTime, Content)
VALUES ('ReactLevel', @@UserKey, GetDate(), 'The Pump is off')
SELECT DateTime, TagName, Content
FROM Annotation
WHERE Annotation.TagName = 'ReactLevel'
AND DateTime > '27 Feb 01'
AND DateTime <= GetDate()

The results are:

DateTime TagName Content


2001-02-28 19:18:00.000 ReactLevel The Pump is off
(1 row(s) affected)

Using Comparison Operators with Delta Retrieval

146 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

The system behaves differently when doing typical delta-based queries where a start date and end
date are specified using the comparison operators >=, >, <= and <. The comparis on operators can be
used on the History and WideHistory tables. The comparison operators also apply regardless of how
the query is executed (for example, four-part naming, OLE DB provider views, and so on).
Delta queries that use the comparison operators return all the valid changes to a set of tags over the
specified time span. Using deadbands and other filters may modify the set of valid changes.

Specifying the Start Date with ">="

If the start date is specified using >= (great er than or equal to), then a row is always returned for the
specified start date. If the start date/time coincides exactly with a valid value change, then the Quality
is normal (0). Otherwise, the value at the start dat e is returned, and the Quality value is 133 (because
the lengt h of time that the tag's value was at X is unknown).
Query 1
For this query, the start date will not correspond to a data change:

SELECT DateTime, Value, Quality


FROM History
WHERE TagName = 'SysTimeMin'
AND wwRetrievalMode = 'Delta'
AND DateTime >= '2001-01-13 12:00:30'
AND DateTime < '2001-01-13 12:10:00'
The start time (12:00:30) does not correspond with an actual change in value, and is therefore marked
with the initial quality of 133:

DateTime Value Quality


2001-01-13 12:00:30.000 0 133
2001-01-13 12:01:00.000 1 0
2001-01-13 12:02:00.000 2 0
2001-01-13 12:03:00.000 3 0
2001-01-13 12:04:00.000 4 0
2001-01-13 12:05:00.000 5 0
2001-01-13 12:06:00.000 6 0
2001-01-13 12:07:00.000 7 0
2001-01-13 12:08:00.000 8 0
2001-01-13 12:09:00.000 9 0
(10 row(s) affected)
Query 2
For this query, the start date will correspond to a data change:

SELECT DateTime, Value, Quality


FROM History
WHERE TagName = 'SysTimeMin'
AND wwRetrievalMode = 'Delta'
AND DateTime >= '2001-01-13 12:01:00'
AND DateTime < '2001-01-13 12:10:00'

Version 17.0.18000 147


Wonderware Historian Retrieval Guide SQL Query Examples

The start time (12:01:00) does correspond exactly with an actual change in value, and is therefore
marked with the normal quality of 0.

DateTime Value Quality


2001-01-13 12:01:00.000 1 0
2001-01-13 12:02:00.000 2 0
2001-01-13 12:03:00.000 3 0
2001-01-13 12:04:00.000 4 0
2001-01-13 12:05:00.000 5 0
2001-01-13 12:06:00.000 6 0
2001-01-13 12:07:00.000 7 0
2001-01-13 12:08:00.000 8 0
2001-01-13 12:09:00.000 9 0
(9 row(s) affected)
Query 3
For this query, the start date will return at least one row, even though the query captures no data
changes:

SELECT DateTime, Value, Quality


FROM History
WHERE TagName = 'SysTimeMin'
AND wwRetrievalMode = 'Delta'
AND DateTime >= '2001-01-13 12:00:30'
AND DateTime < '2001-01-13 12:01:00'
The query does not capture an actual change in value, and is therefore marked with the initial value
quality of 133 for the start time of the query:

DateTime Value Quality


2001-01-13 12:00:30.000 0 133
(1 row(s) affected)

Specifying the Start Date with ">"


If the start date is specified using > (greater than), then the first row returned is the first valid change
after (but not including) the start date. No initial value row is returned. A query that uses > to specify its
start date may return zero rows.
Query 1
For this query, the first row that will be returned will be the first valid change after (but not including) the
start time (12:00: 30):

SELECT DateTime, Value, Quality


FROM History
WHERE TagName = 'SysTimeMin'
AND wwRetrievalMode = 'Delta'
AND DateTime > '2001-01-13 12:00:30'
AND DateTime < '2001-01-13 12:10:00'

148 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

The first row returned is the first valid change after (but not including) the start time (12:00:30):

DateTime Value Quality


2001-01-13 12:01:00.000 1 0
2001-01-13 12:02:00.000 2 0
2001-01-13 12:03:00.000 3 0
2001-01-13 12:04:00.000 4 0
2001-01-13 12:05:00.000 5 0
2001-01-13 12:06:00.000 6 0
2001-01-13 12:07:00.000 7 0
2001-01-13 12:08:00.000 8 0
2001-01-13 12:09:00.000 9 0
(9 row(s) affected)
Query 2
For this query, the start date will correspond to a data change, but it will be excluded from the result set
because the operator used is great er than, not greater than or equal to.

SELECT DateTime, Value, Quality


FROM History
WHERE TagName = 'SysTimeMin'
AND wwRetrievalMode = 'Delta'
AND DateTime > '2001-01-13 12:01:00'
AND DateTime < '2001-01-13 12:10:00'

The start time (12:01:00) corresponds exactly with an actual change in value, but it is excluded from
the result set becaus e the operator used is greater than, not greater than or equal to.

DateTime Value Quality


2001-01-13 12:02:00.000 2 0
2001-01-13 12:03:00.000 3 0
2001-01-13 12:04:00.000 4 0
2001-01-13 12:05:00.000 5 0
2001-01-13 12:06:00.000 6 0
2001-01-13 12:07:00.000 7 0
2001-01-13 12:08:00.000 8 0
2001-01-13 12:09:00.000 9 0
(8 row(s) affected)
Query 3
This query will return no rows, because no dat a changes are captured:

SELECT DateTime, Value, Quality


FROM History
WHERE TagName = 'SysTimeMin'

Version 17.0.18000 149


Wonderware Historian Retrieval Guide SQL Query Examples

AND wwRetrievalMode = 'Delta'


AND DateTime > '2001-01-13 12:00:30'
AND DateTime < '2001-01-13 12:01:00'

The query does not capture an actual change in value; therefore, no rows are returned.

DateTime Value Quality

(0 row(s) affected)

Specifying the End Date with "<="


If the end date is specified using <= (less than or equal to) then the last row returned is the last valid
change up to, and including, the end date. If the end date uses "<=" then the last change returned may
have a date/time exactly at the end dat e. If there is a value exactly at the end dat e, it will be returned.
This query uses the remote table view.

SELECT DateTime, Value, Quality


FROM History
WHERE TagName = 'SysTimeMin'
AND wwRetrievalMode = 'Delta'
AND DateTime > '2001-01-13 12:00:30'
AND DateTime <= '2001-01-13 12:10:00'

Note that there is a valid change at exactly the end time of the query (12:10:00):

DateTime Value Quality


2001-01-13 12:01:00.000 1 0
2001-01-13 12:02:00.000 2 0
2001-01-13 12:03:00.000 3 0
2001-01-13 12:04:00.000 4 0
2001-01-13 12:05:00.000 5 0
2001-01-13 12:06:00.000 6 0
2001-01-13 12:07:00.000 7 0
2001-01-13 12:08:00.000 8 0
2001-01-13 12:09:00.000 9 0
2001-01-13 12:10:00.000 10 0
(10 row(s) affected)

Specifying the End Date with "<"


If the end date is specified using < (less than), then the last row returned is the last valid change up to
(but not including) the end date. If the end date uses "<" then the last event returned will have a
date/time less than the end date. If there is an event exactly at the end date, it will not be returned.
This query uses the remote table view.

SELECT DateTime, Value, Quality


FROM History

150 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

WHERE TagName = 'SysTimeMin'


AND wwRetrievalMode = 'Delta'
AND DateTime > '2001-01-13 12:00:30'
AND DateTime < '2001-01-13 12:10:00'

Note that there is a valid change at exactly the end time of the query (12:10:00), but it is excluded from
the result set.

DateTime Value Quality


2001-01-13 12:01:00.000 1 0
2001-01-13 12:02:00.000 2 0
2001-01-13 12:03:00.000 3 0
2001-01-13 12:04:00.000 4 0
2001-01-13 12:05:00.000 5 0
2001-01-13 12:06:00.000 6 0
2001-01-13 12:07:00.000 7 0
2001-01-13 12:08:00.000 8 0
2001-01-13 12:09:00.000 9 0
(9 row(s) affected)

Using Comparison Operators with Cyclic Retrieval and Cycle


Count

Cyclic queries with the wwCycleCount time domain extension ret urn a set of evenly spaced rows over
the specified time span. The result set will always return the number of rows specified by the cycle
count extension for each tag in the query. The resolution for thes e rows is calculated by dividing the
time span by the cycle count.

Specifying Cycle Count with Two Equity Operators


If the time range is specified using >= and <=, then the first row falls exactly on the start time, and the
last row falls exactly on the end time. In this case, the resolution used is (end date – start date) /
(cyclecount – 1).
This query uses a cycle count of 60, resulting in a 1 second resolution for the data. The query uses the
remot e table view.

SELECT DateTime, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND DateTime >= '2001-01-13 12:00:00'
AND DateTime <= '2001-01-13 12:00:59'
AND wwCycleCount = 60
AND wwRetrievalMode = 'Cyclic'

The results are:

DateTime Value

Version 17.0.18000 151


Wonderware Historian Retrieval Guide SQL Query Examples

2001-01-13 12:00:00.000 0
2001-01-13 12:00:01.000 1
2001-01-13 12:00:02.000 2
2001-01-13 12:00:03.000 3
2001-01-13 12:00:04.000 4
...
2001-01-13 12:00:56.000 56
2001-01-13 12:00:57.000 57
2001-01-13 12:00:58.000 58
2001-01-13 12:00:59.000 59
(60 row(s) affected)

Specifying Cycle Count with One Equity Operator


If one end of the time range is excluded (by using > instead of >= or < instead of <=). then a gap of
"resolution" is left at the beginning (or end) of the result set.
The resolution is calculated as (end dat e – start date) / (cyclecount).
The row that equates to the time which is designated using the < (or >) operator is not returned.
These queries use the remote table view.
Query 1
This query uses a cycle count of 60, resulting in a 1 second resolution for the data. The starting time is
set to >=.

SELECT DateTime, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND wwCycleCount = 60
AND DateTime >= '2001-01-13 12:00:00'
AND DateTime < '2001-01-13 12:01:00'

The results are:

DateTime Value
2001-01-13 12:00:00.000 0
2001-01-13 12:00:01.000 1
2001-01-13 12:00:02.000 2
2001-01-13 12:00:03.000 3
2001-01-13 12:00:04.000 4
...
2001-01-13 12:00:56.000 56
2001-01-13 12:00:57.000 57
2001-01-13 12:00:58.000 58

152 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

2001-01-13 12:00:59.000 59
(60 row(s) affected)
Query 2
This query also uses a cycle count of 60, resulting in a 1 second resolution for the data. The ending
time is set to <=.

SELECT DateTime, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND wwCycleCount = 60
AND DateTime > '2001-01-13 12:00:00'
AND DateTime <= '2001-01-13 12:01:00'

The results are:

DateTime Value
2001-01-13 12:00:01.000 1
2001-01-13 12:00:02.000 2
2001-01-13 12:00:03.000 3
2001-01-13 12:00:04.000 4
...

2001-01-13 12:00:56.000 56
2001-01-13 12:00:57.000 57
2001-01-13 12:00:58.000 58
2001-01-13 12:00:59.000 59
2001-01-13 12:01:00.000 0
(60 row(s) affected)

Specifying Cycle Count with No Equity Operators


If both ends of the time range are excluded (by using > and <) then a gap of "resolution" is left at the
beginning and end of the res ult set.
The resolution is calculated as (end dat e – start date) / (cyclecount + 1).
The row(s) that equate to the start and end times are not returned.
This query uses the remote table view.

SELECT DateTime, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND wwCycleCount = 60
AND DateTime > '2001-01-13 12:00:00'
AND DateTime < '2001-01-13 12:01:01'

The results are:

DateTime Value

Version 17.0.18000 153


Wonderware Historian Retrieval Guide SQL Query Examples

DateTime Value
2001-01-13 12:00:01.000 1
2001-01-13 12:00:02.000 2
2001-01-13 12:00:03.000 3
2001-01-13 12:00:04.000 4
...

2001-01-13 12:00:56.000 56
2001-01-13 12:00:57.000 57
2001-01-13 12:00:58.000 58
2001-01-13 12:00:59.000 59
2001-01-13 12:01:00.000 0
(60 row(s) affected)

Using Comparison Operators with Cyclic Retrieval and


Resolution
Cyclic queries that use comparison operators and the resolution time domain extension ret urn a set of
evenly spaced rows over the specified time span. The resolution for thes e rows is specified in the
query.

Using Two Equality Operators for Comparison with Cyclic Retrieval


and Resolution
If the time range is specified using >= and <=, then the first row falls exactly on the start time. The last
row will fall exactly on the end time, if the resolution divides exactly into the specified time duration. If
the resolution does not divide exactly into the specified time duration, then the last row returned will be
the last row satisfying (start date + N*resolution) which has a timestamp less than the end date.
In short:
 <= endtime MAY return a last row containing the ex act endtime (but it is not guaranteed to do so)
 < endtime is guarant eed NOT to return a last row containing the exact endtime
This q uery sets the resolution to 1 second.

SELECT DateTime, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND wwResolution = 1000
AND DateTime >= '2001-01-13 12:00:00'
AND DateTime <= '2001-01-13 12:01:00'

The results are:

DateTime Value
2001-01-13 12:00:00.000 0
2001-01-13 12:00:01.000 1

154 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

2001-01-13 12:00:02.000 2
2001-01-13 12:00:03.000 3
2001-01-13 12:00:04.000 4
...
2001-01-13 12:00:56.000 56
2001-01-13 12:00:57.000 57
2001-01-13 12:00:58.000 58
2001-01-13 12:00:59.000 59
2001-01-13 12:01:00.000 0
(61 row(s) affected)

Using One Equality Operator for Comparison with Cyclic Retrieval


and Resolution
If the start time is excluded (by using > instead of >=), then a gap of "resolution" is left at the beginning
of the result set. In this case, the first row returned will have the timestamp of the (start date +
resolution). If the end date uses "<" then the last row returned will be the last row defined by (start dat e
+ N*resolution) which has a timestamp less than the end date.
The row that equates to the time that is designated using the < (or >) operator is not ret urned.
Query 1
This query uses a resolution of 1000, resulting in a 1 second resolution for the data.. The starting time
is set to >=.

SELECT DateTime, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND wwResolution = 1000
AND DateTime >= '2001-01-13 12:00:00'
AND DateTime < '2001-01-13 12:01:00'

The results are:

DateTime Value
2001-01-13 12:00:00.000 0
2001-01-13 12:00:01.000 1
2001-01-13 12:00:02.000 2
2001-01-13 12:00:03.000 3
2001-01-13 12:00:04.000 4
...
2001-01-13 12:00:55.000 55
2001-01-13 12:00:56.000 56
2001-01-13 12:00:57.000 57
2001-01-13 12:00:58.000 58

Version 17.0.18000 155


Wonderware Historian Retrieval Guide SQL Query Examples

2001-01-13 12:00:59.000 59
(60 row(s) affected)
Query 2
This query also uses a row resolution of 1000, resulting in a 1 second resolution for the data. The
starting time is set to <=.

SELECT DateTime, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND wwResolution = 1000
AND DateTime > '2001-01-13 12:00:00'
AND DateTime <= '2001-01-13 12:01:00'

The results are:

DateTime Value
2001-01-13 12:00:01.000 1
2001-01-13 12:00:02.000 2
2001-01-13 12:00:03.000 3
2001-01-13 12:00:04.000 4
...

2001-01-13 12:00:56.000 56
2001-01-13 12:00:57.000 57
2001-01-13 12:00:58.000 58
2001-01-13 12:00:59.000 59
2001-01-13 12:01:00.000 0
(60 row(s) affected)

Using No Equality Operators for Comparison with Cyclic Retrieval


and Resolution
If both ends of the time range are excluded (by using > and <), then a gap of resolution is left at the
beginning and end of the res ult set.
The row(s) that equate to the start and end times are not returned.
This query uses a resolution of 1000, resulting in a 1 second resolution for the data.

SELECT DateTime, Value


FROM v_AnalogHistory
WHERE TagName = 'SysTimeSec'
AND wwResolution = 1000
AND DateTime > '2001-01-13 12:00:00'
AND DateTime < '2001-01-13 12:01:01'

The results are:

DateTime Value

156 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

DateTime Value
2001-01-13 12:00:01.000 1
2001-01-13 12:00:02.000 2
2001-01-13 12:00:03.000 3
2001-01-13 12:00:04.000 4
...

2001-01-13 12:00:56.000 56
2001-01-13 12:00:57.000 57
2001-01-13 12:00:58.000 58
2001-01-13 12:00:59.000 59
2001-01-13 12:01:00.000 0
(60 row(s) affected)

Returning Time Between Value Changes

You can return the amount of time before a tag's value changed to a subs equent value. This time is
returned using the wwResolution column.
This functionality works with the cyclic, delta, and full retrieval modes. The delt a and full mode behavior
of wwResolution does not apply to the AnalogSummary History and StateS ummaryHistory tables.
If the time change value is great er than 2,147,000,000 milliseconds (~25 days), then the value of
wwResolution column is -1.
 Example 1: Cyclic Retrieval on page 157
 Example 2: Delt a and Full Retrieval on page 158
 Example 3: Querying the WideHistory Table on page 159
 Example 4: Querying the History Table wit h the wwValueSelector Parameter on page 160
 Example 5: Calc ulating Total Time Bet ween Value Changes on page 161

Example 1: Cyclic Retrieval


For this example, the following data is stored in the Historian:

DateTime Value
2012-01-01 07:59:53 34.42384
2012-01-01 08:00:13 15.02637
2012-01-01 08:00:33 20.29732
2012-01-01 08:00:53 37.40273
2012-01-01 08:01:13 24.31662

Version 17.0.18000 157


Wonderware Historian Retrieval Guide SQL Query Examples

For cyclic retrieval, cycles start at the start DateTime and occur at intervals specified by wwResolution
in the query. If you query for the data 2012 -01-01 08:00:00 to 2012-01-01 08:01: 00 with four cycles,
the wwResolution column in the results show the time in milliseconds until the next point.

DateTime Value wwResolution


2012-01-01 08:00:00 34.42384 20000
2012-01-01 08:00:20 15.02637 20000
2012-01-01 08:00:40 20.29732 20000
2012-01-01 08:01:00 37.40273 20000

Example 2: Delta and Full Retrieval


In delta and full mode, the wwResolution column is used in the query results to show the time in
milliseconds until the next point. When the first point in the result occurs before the query start time, the
wwResolution column shows the time from the start of the query to the next point. If there are no more
points aft er the first point, the wwResolution column is NULL.
For example, the following data is stored:

DateTime Value
2012-01-01 07:59:53 34.42384

If you query for the data bet ween 2012 -01-01 08:00:00 to 2012-01-01 08:00: 10, the results are:
Value wwResolution
DateTime
2012-01-01 08:00:00 34.42384 NULL

However, if the data stored is:


Value
DateTime
2012-01-01 07:59:53 34.42384
2012-01-01 08:00:13 15.02637

Then the results are:


Value wwResolution
DateTime
2012-01-01 08:00:00 34.42384 10000

When the last point in the result occurs before the query end time, the wwResolution column shows the
time until the end of the query when there is a next available point. If there are no more points, then the
wwResolution column shows NULL.
For example, the following is stored:
Value
DateTime
2012-01-01 07:59:53 34.42384
2012-01-01 08:00:13 15.02637

158 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

Value
DateTime
2012-01-01 08:00:33 20.29732
2012-01-01 08:00:53 37.40273
2012-01-01 08:01:13 24.31662

If you query for data from 2012-01-01 08:00:00 to 2012-01-01 08:05: 00, the results are:
Value wwResolution
DateTime
2012-01-01 08:00:00 34.42384 13000
2012-01-01 08:00:13 15.02637 20000
2012-01-01 08:00:33 20.29732 20000
2012-01-01 08:00:53 37.40273 20000
2012-01-01 08:01:13 24.31662 NULL

If you query for data from 2012-01-01 08:00:00 to 2012-01-01 08:01: 00, the results are:
Value wwResolution
DateTime
2012-01-01 08:00:00 34.42384 13000
2012-01-01 08:00:13 15.02637 20000
2012-01-01 08:00:33 20.29732 20000
2012-01-01 08:00:53 37.40273 7000

If the last point happens to be end of the query, then the wwResolution value is zero, even when there
are no more points after the last point. For example, if you query for data from 2012-01-01 08:00:00 to
2012-01-01 08:01:13, the results are:
Value wwResolution
DateTime
2012-01-01 08:00:00 34.42384 13000
2012-01-01 08:00:13 15.02637 20000
2012-01-01 08:00:33 20.29732 20000
2012-01-01 08:00:53 37.40273 20000
2012-01-01 08:01:13 24.31662 0

Example 3: Querying the WideHistory Table


If you execute a query on the WideHistory table for analog tags, wwResolution shows the time
between the first value change for ANY of the tags.

SELECT * FROM OpenQuery(INSQL,'


SELECT DateTime, SysTimeSec, SysTimeMin, wwResolution
FROM WideHistory
WHERE DateTime >= "20120119 12:44:00.000"
AND DateTime <= "20120119 12:45:00.000"
AND wwRetrievalMode = "Delta"

Version 17.0.18000 159


Wonderware Historian Retrieval Guide SQL Query Examples

')

The results are:

DateTime SysTimeSec SysTimeMin wwResolution


2012-01-19 0 44 1000
12:44:00.0000000
2012-01-19 1 44 1000
12:44:01.0000000
2012-01-19 2 44 1000
12:44:02.0000000
2012-01-19 3 44 1000
12:44:03.0000000
2012-01-19 4 44 1000
12:44:04.0000000
2012-01-19 5 44 1000
12:44:05.0000000
...

The wwResolution column shows 1000 milliseconds because the smallest time change is for the
SysTimeSec tag, which is changing every second.
If you run the same query using the SysTimeHour tag instead of the SysTimeS ec tag, the results are:

DateTime SysTimeHour SysTimeMin wwResolution


2012-01-19 12 44 60000
12:44:00.0000000
2012-01-19 12 45 0
12:45:00.0000000

The wwResolution column shows 60000 milliseconds becaus e the smallest time change is for the
SysTimeMin tag, which is changing every minute (every 60 seconds ). Because the query ended at the
time of the last value, a 0 is shown for wwResolution for the ending value.

Example 4: Querying the History Table with the wwValueSelector


Parameter
You can query the History table wit h the wwValueSelector parameter.

SELECT DateTime, TagName, Value, wwResolution


FROM History
WHERE Tagname like 'MyTag'
AND DateTime >= '2012-01-19 10:00:00'
AND DateTime <= '2012-01-19 11:00:00'
AND wwValueSelector = 'STDDEV'

The results are:

DateTime TagName Value wwResolution

160 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

DateTime TagName Value wwResolution


2012-01-19 MyTag 977.157928752564 60000
10:00:00.0000000
2012-01-19 MyTag 16.5619987924163 60000
10:01:00.0000000
2012-01-19 MyTag 16.5619987924163 60000
10:02:00.0000000
2012-01-19 MyTag 16.5619987924165 60000
10:03:00.0000000
2012-01-19 MyTag 16.5619987924163 180000
10:04:00.0000000
2012-01-19 MyTag 16.5619987924171 60000
10:07:00.0000000
2012-01-19 MyTag 16.5619987924163 60000
10:08:00.0000000
2012-01-19 MyTag 16.5619987924179 60000
10:09:00.0000000
2012-01-19 MyTag 16.5619987924163 180000
10:10:00.0000000
2012-01-19 MyTag 16.5619987924195 60000
10:13:00.0000000
2012-01-19 MyTag 16.5619987924163 240000
10:14:00.0000000
2012-01-19 MyTag 16.5619987924226 180000
10:18:00.0000000
2012-01-19 MyTag 16.5619987924163 60000
10:21:00.0000000
2012-01-19 MyTag 16.5619987924226 60000
10:22:00.0000000
2012-01-19 MyTag 16.5619987924038 60000
10:23:00.0000000
...

Example 5: Calculating Total Time Between Value Changes


You can calculate the total time the multiple discrete tags are in a certain state. For example, you want
to know the total time that two pumps were on during a 24-hour period.
The following query returns a dataset that shows the time when both discrete tags had a value of 0:

SELECT * FROM OPENQUERY(INSQL,'


SELECT DateTime, Pump1, Pump2, wwResolution
FROM WideHistory
WHERE DateTime >= "2012-03-08 16:00"
AND DateTime < "2012-03-08 17:00"
AND wwRetrievalMode="DELTA"
')

Version 17.0.18000 161


Wonderware Historian Retrieval Guide SQL Query Examples

WHERE Pump1+Pump2=0

The results are:

DateTime Pump1 Pump2 wwResolution


2012-03-08 16:00:00.0000000 0 0 67
2012-03-08 16:00:01.5980000 0 0 2521
2012-03-08 16:00:04.4470000 0 0 18500
2012-03-08 16:00:23.6000000 0 0 13995
2012-03-08 16:00:37.9140000 0 0 2625
...

The following query shows how to return the total time when both tags had a value of 0:

SELECT SUM(wwResolution) FROM OPENQUERY(INSQL,'


SELECT DateTime, Total=Pump1+Pump2, wwResolution
FROM WideHistory
WHERE DateTime >= "2012-03-08 16:00"
AND DateTime < "2012-03-08 17:00"
AND wwRetrievalMode="DELTA"
')
WHERE Total=0

The results are:

(No column name)


2551289

If you changed the ending WHERE clause to Total> 0, the returned time would be for when more than
one discrete tag was true.

SELECT INTO from a History Table


The following query inserts the specified data from the WideHistory table into another table called
MyTable. Then, the dat a in the My Table table is queried. This query uses the OPENQUE RY function.

DROP TABLE MyTable


SELECT DateTime,
"Sec" = datepart(ss, DateTime),
"mS" = datepart(ms, DateTime),
ReactTemp, ReactLevel
INTO MyTable
FROM OpenQuery(INSQL, 'SELECT DateTime, ReactTemp, ReactLevel FROM
WideHistory
WHERE wwResolution = 5000
AND DateTime >= "2001-03-13 1:58pm"
AND DateTime <= "2001-03-13 2:00pm" ')
SELECT * FROM MyTable

The results are:

162 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

DateTime Sec mS ReactTemp ReactLevel


2001-03-13 13:58:00.000 0 0 190.9 2025.0
2001-03-13 13:58:00.000 5 0 190.9 2025.0
2001-03-13 13:58:00.000 10 0 168.3 1215.0
2001-03-13 13:58:00.000 15 0 168.3 1215.0
2001-03-13 13:58:00.000 20 0 133.8 315.0
2001-03-13 13:58:00.000 25 0 133.8 315.0
2001-03-13 13:58:00.000 30 0 101.6 0.0
2001-03-13 13:58:00.000 35 0 101.6 0.0
2001-03-13 13:58:00.000 40 0 32.4 750.0
2001-03-13 13:58:00.000 45 0 32.4 750.0
2001-03-13 13:58:00.000 50 0 20.9 1700.0
2001-03-13 13:58:00.000 55 0 20.9 1700.0
2001-03-13 13:59:00.000 0 0 85.9 2000.0
2001-03-13 13:59:00.000 5 0 85.9 2000.0
2001-03-13 13:59:00.000 10 0 185.9 2000.0
2001-03-13 13:59:00.000 15 0 185.9 2000.0
2001-03-13 13:59:00.000 20 0 168.3 1235.0
2001-03-13 13:59:00.000 25 0 168.3 1235.0
2001-03-13 13:59:00.000 30 0 136.1 335.0
2001-03-13 13:59:00.000 35 0 136.1 335.0
2001-03-13 13:59:00.000 40 0 103.9 -25.0
2001-03-13 13:59:00.000 45 0 103.9 -25.0
2001-03-13 13:59:00.000 50 0 34.7 625.0
2001-03-13 13:59:00.000 55 0 34.7 625.0
2001-03-13 14:00:00.000 0 0 20.9 1575.0
(25 row(s) affected)

Moving Data from a SQL Server Table to an Extension Table

The following queries show how to insert manual data int o a normal SQL Server table and then move it
into the History extension table.
First, insert the data into the SQL Server table. The following query inserts two minutes of existing data
for the SysTimeS ec tag into the ManualAnalogHistory table:

INSERT INTO ManualAnalogHistory (DateTime, TagName, Value, Quality,


QualityDetail, wwTagKey)
SELECT DateTime, TagName, Value, Quality, QualityDetail, wwTagKey
FROM History WHERE TagName = 'SysTimeSec'
AND DateTime >= '20050329 12:00:00'

Version 17.0.18000 163


Wonderware Historian Retrieval Guide SQL Query Examples

AND DateTime <= '20050329 12:02:00'


Then, create a manual tag using the System Management Console. For a manual tag, "MDAS/Manual
Acquisition" is specified as the acquisition type. Be sure to commit the changes to the sy stem. In this
example, a manual analog tag named MDAS1 was created.
Finally, insert the data from the ManualAnalogHistory table into History:

INSERT INTO History (TagName, DateTime, Value, QualityDetail)


SELECT 'MDAS1', DateTime, Value, QualityDetail FROM ManualAnalogHistory
WHERE TagName = 'SysTimeSec'
AND DateTime >= '20050329 12:00:00'
AND DateTime <= '20050329 12:02:00'

Using Server-Side Cursors

Curs ors are a very powerful feature of SQL Server. They permit cont rolled movement through a record
set that results from a query.
For in-depth information on cursors, see your Micros oft SQL Server documentation.
The Wonderware Historian OLE DB Provider pr ovides server-side cursors. Cursors can be used to do
joins that are not possible in any other way. They can be used to join dat e/times from any source with
date/times in the history tables.
The following query provides an ex ample of using a server-side cursor. This query:
 Fetches all of the events in the E ventHistory table.
 Shows a "snapshot" of three tags at the time of each event.
 Shows the event tag and its associated key value.
This query could easily be encapsulated int o a stored procedure. The query uses the four-part naming
convention.

SET QUOTED_IDENTIFIER OFF


DECLARE @DateValue DateTime
DECLARE @EventTag nvarchar(256)
DECLARE @EventKey int
DECLARE @Qry1 nvarchar(500)
DECLARE @Qry2 nvarchar(500)
DECLARE @Qry3 nvarchar(500)
SELECT @Qry1 = N'SELECT EventTag = @EventTag, EventKey = @EventKey, DateTime,
TagName, Value, Quality
FROM History
WHERE TagName IN (N''SysTimeSec'', N''SysTimeMin'', N''SysTimeHour'')
AND DateTime = '''
SELECT @Qry2 = N''''
SELECT @Qry3 = N''
DECLARE Hist_Cursor CURSOR FOR
SELECT DateTime, TagName, EventLogKey
FROM Runtime.dbo.EventHistory
OPEN Hist_Cursor
FETCH NEXT FROM Hist_Cursor INTO @DateValue, @EventTag, @EventKey
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @Qry3 = @Qry1 + convert(nvarchar, @DateValue, 121) + @Qry2
--PRINT @Qry3
EXEC sp_executesql @Qry3, N'@EventTag nvarchar(256),

164 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

@EventKey int', @EventTag, @EventKey


FETCH NEXT FROM Hist_Cursor INTO @DateValue, @EventTag, @EventKey
END
CLOSE Hist_Cursor
DEALLOCATE Hist_Cursor
The results are:

EventTag Event DateTime TagName Value Quality


Key
SysStatusEvent 3 2001-01-12 SysTimeSec 27.0 0
13:00:27.000
SysStatusEvent 3 2001-01-12 SysTimeMin 0.0 0
13:00:27.000
SysStatusEvent 3 2001-01-12 SysTimeHour 13.0 0
13:00:27.000
(3 row(s) affected)

EventTag Event DateTime TagName Value Quality


Key
SysStatusEvent 4 2001-01-12 SysTimeSec 28.0 0
14:00:28.000
SysStatusEvent 4 2001-01-12 SysTimeMin 0.0 0
14:00:28.000
SysStatusEvent 4 2001-01-12 SysTimeHour 14.0 0
14:00:28.000
(3 row(s) affected)

Using Stored Procedures in OLE DB Queries

Any normal SQL Server stored procedure can make use of the tables exposed by the Wonderware
Historian OLE DB Provider. Stored procedures can use any valid Transact -SQL syntax to access
Wonderware Historian historical data.
In other words, stored procedures can make use of four-part -queries, OPENQUERY and
OPENROWSET functions, cursors, parameterized queries and views. Stored proc edures can be used
to encapsulate complex joins and ot her operations for easy re -use by applications and end users.

Getting Data from the OPCQualityMap Table

In general, an OPC quality has 16 significant bits. The lower 8 bits contain the quality as described in
the table, while the upper 8 bits hold server -specific information. To ens ure correct results, it is
important to consider only the lower 8 bits in a query or join involving the OP CQualityMap table.
For example:

SELECT h.DateTime, h.TagName, h.Value, o.Description FROM History h


INNER JOIN OPCQualityMap o
ON (h.OPCQuality & 255) = o.OPCQuality
WHERE TagName in (…)
AND …

Version 17.0.18000 165


Wonderware Historian Retrieval Guide SQL Query Examples

Using Variables with the Wide Table

You cannot use variables in an OPENQUERY statement. Therefore, if you want to use variables in a
query on the wide table, you must first build up the OPE NQUERY statement "on the fly" as a string,
and then execute it.

DECLARE @sql nvarchar(1000)


DECLARE @DateStart datetime

DECLARE @DateEnd datetime

SET @DateStart = '2001-8-29 11:00:00'


SET @DateEnd = '2001-8-29 11:11:00'

SET @sql = N'select *

FROM OPENQUERY(INSQL, ''SELECT DateTime, ReactLevel, ReactTemp, ProdLevel,


BatchNumber, ConcPump, Mixer, TransferValve, TransferPump, WaterValve,
ConcValve, OutputValve, SteamValve
FROM WideHistory
WHERE DateTime >= "' + CONVERT(varchar(26), @DateStart, 113) + '"
and DateTime <= "' + CONVERT(varchar(26), @DateEnd, 113) + '"
AND wwResolution = 1000
AND wwRetrievalMode = "cyclic"'') '

EXEC sp_executesql @sql

Retrieval Across a Data Gap in Classically Stored Data


For blocks created by the Classic Storage subsystem, if the data to be retrieved spans more than one
history block, and the start time of the later block is equal (within one tick) to the end time of the first
block, you will not notice any difference than when querying within a single block.

166 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

However, if the system was stopped between history blocks, there will be a gap in the data, as shown
in the following diagram:

Upon ret rieval, additional data points (labeled A and B) will be added to mark the end of the first block's
data and the beginning of the second block's data. Point C is a stored point generat ed by the Storage
subsystem. (Upon a restart, the first value from each IDAS will be offset from the start time by 2
seconds and have a quality detail of 252.)
The following paragraphs explain this in more detail.
For delta retrieval, the data values in the first block are returned as stored. After the end of the block is
reached and all of the points have been retrieved, an additional data point (A) will be insert ed by
retrieval to mark the end of the dat a. The value for point A will be

Point A attribute Value(Hex) Value(Dec)

Value 0 0

Quality 100 256

Quality Detail 0 0

If there is no value stored at the beginning of the next block, an initial data point (B) will be inserted by
retrieval and will have the snapshot initial value as stored. The quality and quality detail values are as
follows:

Point B attribute Value(Hex) Value(Dec)

Value Snapshot Snapshot

Quality 0 0

Quality Detail 96 150

Version 17.0.18000 167


Wonderware Historian Retrieval Guide SQL Query Examples

In the case of cyclic retrieval, a point is required for each specified time. If the time coincides with the
data gap, a NULL point for that time will be generated. The inserted points will have the values defined
in the following table.

Cyclic NULL point Value(Hex) Value(Dec)

Value 0 0

Quality 100 256

Quality Detail 0 0

If you are using time or value deadbands for delta ret rieval across a data gap, the behavior is as
follows:
 For a value deadband, all NULLs will be returned and all values immediately after a NULL will be
returned. That is, the deadband is not applied to values separated by a NULL.
 For a time deadband, null values are treated like any other value. Time deadbands are not affected
by NULLs.

Returned Values for Non-Valid Start Times


One example of a non-valid query start time is a start time that is earlier than the start time of the first
history block. For delta retrieval, the first row returned will be NULL. The timestamp will be that of the
query start time. The next row returned will be timestamped at the start of the history block and have
the following attributes:

Point attribute Value(Hex) Value(Dec)

Value Snapshot Snapshot

Quality 0 0

Quality Detail 96 150

For cyclic retrieval, NULL will be returned for data values that occur before the start of the history
block.
Another non-valid start time is a start time that is later than the current time of the Wonderware
Historian comput er. For delta retrieval, a single NULL value will be returned. For cyclic retrieval, a
NULL will be ret urned for each data value requested.

Querying Aggregate Data in Different Ways


There are four different ways you can retrieve summary data, such as an average, using the Historian.
 Using the SQL Server average function. This is appropriate for discrete samples. For example, a
check weigher, where you are measuring individual units against a target weight.
 Using the average retrieval mode. This is appropriate for most situations where you want to find an
average, as it is weighted according to time. For example, if you want to find the average for a flow
rate or a temperature.
 Setting up summary replication and then querying the AnalogSummaryHistory table. Replication
uses the average retrieval mode to do the calculations.
 Setting up a summary event and then querying the SummaryData table. The E vent subsystem
uses the SQL Server average function.

168 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

The following examples show how you can get the same data using these different met hods. All
examples use the SysTimeSec system tag, which has a range of 0 to 59.
Query 1
The following query uses the SQL Server average function to return the average value of the
SysTimeSec tag over the span of one minute.

SELECT AVG(Value) as 'SysTimeSec AVG'


FROM History
WHERE TagName = 'SysTimeSec'
AND DateTime > '2009-11-15 6:30:00'
AND DateTime < '2009-11-15 6:31:00'
AND wwRetrievalMode = 'Full'

The results are:

SysTimeSec AVG
29.5

Query 2
The following query uses the historian time-weighted average retrieval mode to return the average for
the same time period. Because the cycle count is set to 2, a first row is returned for the "phantom"cycle
leading up to the query start time. The StartDateTime column shows the time stamp at the start of the
data sampling, which is the start time of the phantom cycle. The second row ret urned reflects is the
actual data that you expect. The time stamp for the data value is 2009 -11-15 06: 31:00 because the
default time stamping rule is set so that the ending time stamp for the cycle is returned. For more
information about the phantom cycle, see About Phantom Cycles on page 94.

SELECT StartDateTime, DateTime, TagName, Value


FROM History
WHERE TagName = 'SysTimeSec'
AND DateTime >= '2009-11-15 6:30:00'
AND DateTime <= '2009-11-15 6:31:00'
AND wwRetrievalMode = 'Average'
AND wwCycleCount = 2
AND wwTimeStampRule = 'end'

The results are:

StartDateTime DateTime TagName Value


2009-11-15 06:29:00 2009-11-15 06:30:00 SysTimeSec 29.5
2009-11-15 06:30:00 2009-11-15 06:31:00 SysTimeSec 29.5
Query 3
For the following query, local replication has been set up so that the average of the SysTimeSec tag is
calculated every minute and stored to the SysTimeSec.1M analog summary tag. The query ret urns the
value of the SysTimeSec.1M tag for the time period specified.

SELECT TagName, StartDateTime, EndDateTime, Average as AVG


FROM AnalogSummaryHistory
WHERE TagName = 'SysTimeSec.1M'
AND StartDateTime >= '2009-11-15 6:30:00'

Version 17.0.18000 169


Wonderware Historian Retrieval Guide SQL Query Examples

AND EndDateTime <= '2009-11-15 6:31:00'

The results are:

TagName StartDateTime EndDateTime AVG


SysTimeSec.1M 2009-11-15 06:30:00 2009-11-15 06:31:00 29.5
Query 4
The following query, the History table is used instead of the AnalogS ummaryHistory table. Because the
cycle count is set to 2, this query returns a row for the phantom cycle. The time stamp for the data
value is 2009-11-15 06:31:00 because the default time stamping rule is set so that the ending time
stamp for the cycle is returned.

SELECT TagName, DateTime, Value


FROM History
WHERE TagName = 'SysTimeSec.1M'
AND DateTime >= '2009-11-15 6:30:00'
AND DateTime <= '2009-11-15 6:31:00'
AND wwRetrievalMode = 'avg'
AND wwCycleCount = 2

The results are:

TagName DateTime Value


SysTimeSec.1M 2009-11-15 06:30:00 29.5
SysTimeSec.1M 2009-11-15 06:31:00 29.5
Query 5
The following query returns five minutes of summary data for an event tag that has been configured to
store the average value of the Sys TimeSec tag every minute.

SELECT TagName, CalcType, SummaryDate, Value


FROM v_SummaryData
WHERE TagName = 'SysTimeSec'
AND SummaryDate >= '2009-11-15 18:30:00'
AND SummaryDate <= '2009-11-15 18:31:00'

The results are:

TagName CalcType SummaryDate Value


SysTimeSec AVG 2009-11-15 18:30:00.000 29.5
SysTimeSec AVG 2009-11-15 18:31:00.000 29.5

Bitwise Retrieval for Process Data


It is common to pack multiple digital states into the same PLC register as an integer rather than as
individual bits. You can still map the individual bits to separat e Historian tags for most
DAServers/PLCs, but if you instead map the entire integer to a single Historian tag, you can address
individual bits using standard SQL Server queries.

170 Version 17.0.18000


SQL Query Examples Wonderware Historian Retrieval Guide

For example, consider the following query that ret urns process data values for the ’SysTimeMin’ tag:

SELECT Value FROM dbo.History WHERE TagName = 'SysTimeMin'


However to get more bits of data, you can add 2 (bitposition -1) and use bitwise & operator on the
Value column as shown in the following query. Using the the Integer cast, you can query a maximum of
32 bits.

SELECT
CONVERT(BIT, CAST(Value AS INT) & 1) As 'Bit0',
CONVERT(BIT, CAST(Value AS INT) & 2) As 'Bit1',
CONVERT(BIT, CAST(Value AS INT) & 4) As 'Bit2',
CONVERT(BIT, CAST(Value AS INT) & 8) As 'Bit3',
CONVERT(BIT, CAST(Value AS INT) & 16) As 'Bit4',
CONVERT(BIT, CAST(Value AS INT) & 32) As 'Bit5',
CONVERT(BIT, CAST(Value AS INT) & 64) As 'Bit6',
CONVERT(BIT, CAST(Value AS INT) & 128) As 'Bit7'
FROM dbo.History WHERE TagName = 'SysTimeMin'

The results are:

Bit1 Bit2 Bit3 Bit4 Bit5 Bit6 Bit7 Bit8


0 1 1 0 0 0 0 0
1 1 1 0 0 0 0 0
0 0 0 1 0 0 0 0
1 0 0 1 0 0 0 0
0 1 0 1 0 0 0 0
1 1 0 1 0 0 0 0
0 0 1 1 0 0 0 0

1 0 1 1 0 0 0 0
0 1 1 1 0 0 0 0
1 1 1 1 0 0 0 0

Version 17.0.18000 171


Wonderware Historian Retrieval Guide

C HAPTER 4
SQL Queries for Alarms and Events
Note: The alarm and event history functionality described in this chapter captures detailed histories
from Application Server. This functionality should not be confused with the Classic E vent subsystem
allows for some basic events tracking and is based on historical data.

Wonderware Historian captures process data about your plant. In addition to real-time and historical
data, this includes information about events.
E vents are like other process data – for example, temperature – because their values can change over
time. Events differ from other process data in these ways:
 E vents usually change more slowly.
 E vents usually are more complex than simply a value, time, and quality.
E vent data ans wers questions like "When did this setpoint change and who changed it?" The event
record could include the nam e of the operator, the workstation from where the change was made, any
comment about the change, the name of the person who verified the change, and other related details.
Alarms are a specific kind of event. They represent state changes and have an associ ated lifecycle.
This lifecycle includes these states (usually in this order):
 Set – For example, when a temperature goes too high.
 Acknowledged – That is, when an operator rec ognizes it as an alarm and, ideally, addresses it.
 Clear – For example, when the temperature returns to normal.
Alarms may also have other states, but these are the key ones.
You can query the E vents view, which references the History table, to track and analyze alarms and
other events. Because E vents is actually an extension table (like History), its data is stored in blocks,
not in SQL Server tables.
Note: The E vents view does not expose all application-specific columns that may be stored by
Historian. (Such columns are queryable from the REST/ OData interface.) Also, it is not unusual for
E vents columns to contain many NULL values.

For more information about the E vents view, see E vents in the Wonderware Historian Database
Referenc e.

In This Chapter
Querying Alarms and E vents ....................................................................................................... 173

Querying Alarms and Events


Querying Alarm and E vent data is helpful in keeping track of your production environment. For
example, as an operator, you could query the data to find out ans wers to these questions:
 How often alarm events occur?

Version 17.0.18000 173


Wonderware Historian Retrieval Guide SQL Queries for Alarms and Events

 Where in the facility they occur?


 How critical the alarms are?
 How quickly they are addressed and cleared?

Datetime in Alarm and Event Queries


All queries of alarm and event data must include at least one datetime column.
Alarm and event queries use two ways to express time:
 UTC time
This format is used by E ventTimeUtc.
 Local time for the location of the Historian server
This is used by columns like Event Time.
The value of wwTimeZone affects any datetime recorded in local time, but does not affect
E vent TimeUtc.

Example: Listing all events


One of the simplest queries for alarms and events data is to get a list of all events.
For example,a query like this one would list all events between the dates and times specified:

SELECT *
FROM Events
WHERE EventTime between '2015-10-25 0:00' and '2015-10-26 0:00'

Example: How often alarms occur


This query reports the average alarm rate on hourly basis.

DECLARE @StartTime as varchar(60)


DECLARE @EndTime as varchar(60)
SET @StartTime = '2015-10-25 12:00:00'
SET @EndTime = '2015-10-26 12:00:00'

DECLARE @AlarmRaise table


(
EventTime nvarchar(60),
ID nvarchar(50),
AlarmState nvarchar(20),
SourceArea nvarchar(20),
SourceObject nvarchar(20)
)
INSERT @AlarmRaise select
EventTime,Alarm_ID,Alarm_State,Source_Area,Source_Object from Events where
EventTime > @StartTime and EventTime < @EndTime and Alarm_State='UNACK_ALM'
--======================--

DECLARE @AlarmCounts table


(
ForDate nvarchar(60),
OnHour nvarchar(50),
CountperHour nvarchar(20)

174 Version 17.0.18000


SQL Queries for Alarms and Events Wonderware Historian Retrieval Guide

INSERT @AlarmCounts SELECT CAST(EventTime as date) AS ForDate,


DATEPART(hour,EventTime) AS OnHour,
Count(*) AS "CountperHour"
FROM @AlarmRaise
GROUP BY CAST(EventTime as date),
DATEPART(hour,EventTime)

SELECT Avg(CAST(CountperHour as INT)) as "Average Alarm Rate on Hourly Basis"


from @AlarmCounts
The resulting report looks like this:

Average Alarm Rate on Hourly Ba si s

Example: Most frequent alarm per hour


This query reports the most frequent alarms for each hour:

DECLARE @StartTime as varchar(60)


DECLARE @EndTime as varchar(60)
SET @StartTime = '2015-10-25 12:00:00'
SET @EndTime = '2015-10-26 12:00:00'

DECLARE @AlarmRaise table


(
EventTime nvarchar(60),
ID nvarchar(50),
AlarmState nvarchar(20),
SourceArea nvarchar(20),
SourceObject nvarchar(20),
SourceConditionVariable nvarchar(40)
)
INSERT @AlarmRaise select
EventTime,Alarm_ID,Alarm_State,Source_Area,Source_Object,Source_Condition
Variable from Events where EventTime > @StartTime and EventTime < @EndTime
and Alarm_State='UNACK_ALM'
--======================--
SELECT CAST(EventTime as date) AS ForDate,
DATEPART(hour,EventTime) AS OnHour,
Count(*) AS "Count per Hour",
SourceObject + SourceConditionVariable AS "Alarm Attribute"

FROM @AlarmRaise
GROUP BY CAST(EventTime as date),
DATEPART(hour,EventTime),
SourceObject,
SourceConditionVariable
ORDER BY ForDate ASC,OnHour,[Alarm Attribute]

This results in two reports. The first looks like this:

Version 17.0.18000 175


Wonderware Historian Retrieval Guide SQL Queries for Alarms and Events

Hour Severity Average Unacknowleged Count

00:00. 0 1 586277 6
00:00. 0 2 391149 5
00:00. 0 3 NULL 1
00:00. 0 1 152862 4
00:00. 0 2 19962 5
00:00. 0 3 NULL 1
00:00. 0 1 366367 4
00:00. 0 2 366370 2
… … … …

The second report looks like this:

Hour Average Unacknowleged User Name Count

00:00. 0 488713 Administrator 12


00:00. 0 64262 Administrator 10
00:00. 0 366368 Administrator 6
00:00. 0 49129 Administrator 4
00:00. 0 332972 lmadmin 1
00:00. 0 99805 lmadmin 8
00:00. 0 5672504 DefaultUser 1
00:00. 0 5874430 DefaultUser 1
… … … …

Example: Pinpointing where alarms occur


This query reports the number of alarms raised from each source by area and by object.

DECLARE @StartTime as varchar(60)


DECLARE @EndTime as varchar(60)
SET @StartTime = '2015-10-25 12:00:00'
SET @EndTime = '2015-10-26 12:00:00'

DECLARE @AlarmRaise table


(
EventTime nvarchar(60),
ID nvarchar(50),
AlarmState nvarchar(20),
SourceArea nvarchar(20),
SourceObject nvarchar(20)
)

176 Version 17.0.18000


SQL Queries for Alarms and Events Wonderware Historian Retrieval Guide

INSERT @AlarmRaise select


EventTime,Alarm_ID,Alarm_State,Source_Area,Source_Object from Events where
EventTime > @StartTime and EventTime < @EndTime and Alarm_State='UNACK_ALM'
--======================--
SELECT SourceArea AS "Source Area/Object" , count(*) AS "Total Number of
Alarms" from @AlarmRaise GROUP BY SourceArea UNION
SELECT SourceObject AS "Source Area/Object" , count(*) AS "Total Number of
Alarms" from @AlarmRaise GROUP BY SourceObject;

The results look like this:

Source Area/Object Total Number of Alarms

Area_001 6
UserDefined_001 6

Example: Showing average time to clearing an alarm


This query reports the average time to clear Critical, High, Medium, and Low alarms per hour.

DECLARE @start DateTime2


SET @start = '2014-10-27'
DECLARE @end DateTime2
SET @end = '2015-10-27'

-- ack time per severity per hour for high, medium and low
SELECT DATEADD(hour, DATEDIFF(hour, 0, e.EventTime), 0) as hour,
e.Severity,
avg(Alarm_UnAckDurationMs) as avg_unack,
count(*) as count
FROM Events e
WHERE
e.EventTime < @end
AND e.EventTime >= @start
AND e.Severity <=3 -- critical = 1, high = 2 medium = 3 low =
4
AND e.Type = 'Alarm.Acknowledged'
GROUP BY
DATEADD(hour, DATEDIFF(hour, 0, e.EventTime), 0),
severity
ORDER BY
DATEADD(hour, DATEDIFF(hour, 0, e.EventTime), 0),
e.severity

-- ack time by user by hour


SELECT DATEADD(hour, DATEDIFF(hour, 0, e.EventTime), 0) as hour,
avg(Alarm_UnAckDurationMs) as avg_unack,
e.User_Name,
count(*) as count
FROM Events e
WHERE
e.EventTime < @end
AND e.EventTime >= @start

Version 17.0.18000 177


Wonderware Historian Retrieval Guide SQL Queries for Alarms and Events

AND e.Type = 'Alarm.Acknowledged'


GROUP BY
DATEADD(hour, DATEDIFF(hour, 0, e.EventTime), 0),
e.User_Name
ORDER BY
DATEADD(hour, DATEDIFF(hour, 0, e.EventTime), 0),
e.User_Name

This query results in two reports. The first one looks like this:

Hour Severity Average Acknowledged Count

00:00. 0 1 586277 6
00:00. 0 2 391149 5
00:00. 0 3 NULL 1
00:00. 0 1 152862 4
00:00. 0 2 19962 5
00:00. 0 3 NULL 1
00:00. 0 1 366367 4
00:00. 0 2 366370 2

… … … …

The second report looks like this:

Hour Average Acknowledged User Name Count

00:00. 0 488713 Administrator 12


00:00. 0 64262 Administrator 10
00:00. 0 366368 Administrator 6
00:00. 0 49129 Administrator 4
00:00. 0 332972 lmadmin 1
00:00. 0 99805 lmadmin 8
00:00. 0 5672504 DefaultUser 1
00:00. 0 5874430 DefaultUser 1
… … … …

Example: Evaluating response time for alarms


This query reports when an alarm is raised, acknowledged, and cleared. The report lists both times
and duration.

DECLARE @StartTime as varchar(60)


DECLARE @EndTime as varchar(60)

178 Version 17.0.18000


SQL Queries for Alarms and Events Wonderware Historian Retrieval Guide

SET @StartTime = '2015-10-25 12:00:00'


SET @EndTime = '2015-10-26 12:00:00'

DECLARE @AlarmRaise table


(
EventTime nvarchar(60),
ID nvarchar(50),
AlarmState nvarchar(20)
)
INSERT @AlarmRaise
SELECT EventTime,Alarm_ID,Alarm_State
FROM Events
WHERE EventTime > @StartTime and EventTime < @EndTime and
Alarm_State='UNACK_ALM'

DECLARE @AlarmAck table


(
EventTime nvarchar(60),
ID nvarchar(50),
UnAckDuration nvarchar(20)
)
INSERT @AlarmAck
SELECT EventTime,Alarm_ID,Alarm_UnAckDurationMs
FROM Events
WHERE EventTime > @StartTime and EventTime < @EndTime and
Alarm_Acknowledged=1

DECLARE @AlarmClear table


(
EventTime nvarchar(60),
ID nvarchar(50),
AlarmDuration nvarchar(20)
)
INSERT @AlarmClear
SELECT EventTime,Alarm_ID,Alarm_DurationMs
FROM Events
WHERE EventTime > @StartTime and EventTime < @EndTime and
Type='Alarm.Clear'

--======================--
SELECT 'Alarm Life - '+ s.ID
,CASE
WHEN a.EventTime > c.EventTime THEN 'Cleared Before
Ack'
WHEN a.EventTime < c.EventTime THEN 'Acked Before
Clear'
ELSE '-' END as Comment
,s.EventTime as AlarmRaised
,a.EventTime as AlarmAcked
,c.EventTime as AlarmClear
,a.UnAckDuration as UnAckDuration
,c.AlarmDuration as AlarmDuration

FROM (@AlarmRaise s inner join @AlarmClear c on c.ID=s.ID)


LEFT JOIN @AlarmAck a on a.ID=c.ID and a.EventTime<>c.EventTime
ORDER BY AlarmRaised asc
The results look like this:
Version 17.0.18000 179
Wonderware Historian Retrieval Guide SQL Queries for Alarms and Events

Alarm Alarm Alarm Unack Alarm


Comment Raised Ack’d Cleared Duration Duration

Alarm Life -
B8A45440-3950-52F9-3040-0
0E8158D06BB - 22:40. 0 NULL 22:43. 0 NULL 3005

180 Version 17.0.18000


Wonderware Historian Retrieval Guide

C HAPTER 5
Browser-Friendly Data Retrieval
In This Chapter
About Data Retrieval Using the iHistory Interface .......................................................................... 181
Querying the Historian Dat abas e ................................................................................................. 182
Using the Excel OData Feed to Import Process or E vent Dat a ....................................................... 186
Querying History Blocks via SQL S erver Reporting Services Extension .......................................... 188
Supported OData Retrieval Syntax .............................................................................................. 189
Resources .................................................................................................................................. 193
Summary Resources .................................................................................................................. 199
E vent Resources ........................................................................................................................ 206
Errors......................................................................................................................................... 211

About Data Retrieval Using the iHistory Interface


Wonderware Historian's web service int erface, iHistory, allows data retrieval from client applications,
including browser-based client applications. Some examples of client applications that use the iHistory
interface to retrieve data are:
 Wonderware Online InSight
This cloud-based product returns data queries through iHistory.
 Wonderware Historian InSight
This is the on-premises version of Wonderware Online InSight and is a client tool included wit h
Wonderware Historian.
 Wonderware Historian Client
This application uses iHistory to access Wonderware Online InSight.
 Wonderware SmartGlance
This product runs on mobile devices. When used with Wonderware Online InSight, it uses iHistory
to query the historical data needed for its mobile reports.

About the OData Web Protocol


The iHistory interface uses the Open Data (OData) web protocol, an industry standard for querying and
updating data. OData can expose and access information from a variety of sources, such as relational
databases, file systems, content management systems, and traditional websites.
Historian's implement ation of OData includes a few restrictions:
 JSON and atom formats are supported.
 ODat a versions 3 and 4 are supported.

Version 17.0.18000 181


Wonderware Historian Retrieval Guide Browser-Friendly Data Retrieval

 A subset of the OData system query options is supported. For more information, see Supported
Syntax Tok ens and Operators on page 191.

Tip: For optimum viewing of the data returned by the OData interfac e, we rec ommend using the
JSONView viewer in the Chrome browser.

iHistory and Account Authentication


The iHistory web service requires users to be aut henticated via a login proc ess before they can
retrieve data. The process for this differs bet ween Wonderware Historian InSight and Wonderware
Online InSight:
 Wonderware Historian InSight (on-premise s)
Uses Windows integrated security. A user must belong to the aaAdministrators, aaP owerUsers, or
aaUs ers Windows group. The iHistory web service uses Negotiate authentication, which is
supported by most modern browsers and web service clients (such as Microsoft Excel).
 Wonderware Online InSight (cloud-ba sed)
Uses OpenID Connect and Basic authentication. Users must be invited to a specific account within
Wonderware Online InSight and can then access all data published to that account. When using
OpenID Connect, the iHistory web service uses "bearer token" authentication, per the OpenID
Connect standard. As relatively new standard, some web service clients (for example, Microsoft
Excel) do not have native support for it. However, some of those same clients (for exam ple,
Microsoft Power BI) support Basic authentication.
When you query on-premises data via iHistory, you will be prompted for aut hentication to the Historian.
 If you have a valid Windows login on the historian, you can retrieve general information about the
services and the kinds of data available.
 If you belong to the aaAdministrators, aaPowerUsers, or aaUsers Windows group, you can retrieve
actual application data -- including events, process history, tag information, and so on.

Querying the Historian Database


The iHistory web service int erface uses URLs for the queries. There are several different entities
(whic h correspond to tables or views in a relational database) that you can query.
To see the full list of available entities, use the following queries.
 From an on-premise s hi storian, type:

http://<host>:<port>/Historian/<ver>/$metadata
where:
o <host> and <port> specify the name and port used by the on -premises historian for Historian
InSight
o <ver> is the version number -- either " v1" or " v2".
 For Wonderware Online InSight, type:

https://online.wonderware.com/apis/historian/7.8/$metadata

Using Date Time Filters


To avoid unbounded results, all entities that return timestamped dat a apply a filter on the timestamp. If
the actual query does not include a filter on the timestamp, the default filter of "last one hour" is
applied. Similarly, if only one time filter is specified (rather than both a start and end time), the duration
defaults to one hour.

182 Version 17.0.18000


Browser-Friendly Data Retrieval Wonderware Historian Retrieval Guide

All date-times used in the iHistory web service are expressed in UTC. They all use the ISO 8601
format and the OData datetimeoffset data type.

Note: Use "%20" to indicate a space. Use "%27" to indicate a single quote.
If you are using the JSONView viewer in the Chrome browser, you can use a plus sign (+) to indicate a
space to make the URI string more readable.

How you use date-time filters for process history, event data, and summary history varies:
 Process hi story
For example, to filter based on a time range, you can include the following in your query:


DateTime+ge+datetimeoffset%272014-07-04T00:00:00.000Z%27+and+DateTime+le+
datetimeoffset%272014-07-04T12:00:00.000Z%27

The example above uses the DateTime property of the ProcessValues entity.
 Event data
The E vent entity has a corresponding property called E vent Time that works similarly to DateTime
in the example above.
 Summary history
By contrast, the Summary entity uses separat e StartDat eTime and EndDataTime properties. For
example:


StartDateTime+ge+datetimeoffset%272014-07-04T00:00:00.000Z%27+and+EndDate
Time+le+datetimeoffset%272014-07-04T12:00:00.000Z%27

Process History Query Options


You can retrieve historiz ed process data stored in history blocks via iHistory. Queries for process
history can include these additional query string parameters:

Parameter Used for

Resolution Defines the resample interval (in milliseconds) to apply to the data. Applies to
Summaries and (depending on the mode) ProcessValues entities and the
Tag/Raw navigation property.
For example, to return hourly summaries for a day, set the start and end tim es to
report midnight to midnight, and the res olution to 3600000 (1 -hour).
The default resolution is 1 minut e.

Version 17.0.18000 183


Wonderware Historian Retrieval Guide Browser-Friendly Data Retrieval

RetrievalMode Cont rols the res ampling method to apply to the results. Applies to the
ProcessValues entity and the Tag/ Raw navigation property. Support ed values
include:
 Cyclic
 Delta
 Full
 Interpolated
 BestFit (the default)
 A verage
 Min
 Max
 Integral
 Slope
 Counter

Event Data Query Options


You can retrieve alarm and event data stored in history blocks via iHistory.
In addition to the alarm and event data in history blocks, other alarm and event data is stored in these
locations and is not accessible via the Historian's OData interface:

A&E data stored here Retrieved this way

Runtime database (stored by the Classic Using SQL queries. For more information, see Edge
E vents subsystem) Detection for Events (wwE dgeDetection) on page 78.
A2ALMDB database Using SQL queries

Note: Earlier versions of Wonderware System Platform used WWALMDB dat abas e rather than
A2ALMDB for alarms and events. If you are currently using WWALMDB and want to to use A2ALMDB
instead, you may need to change your alarm historization settings from within the ArchestrA IDE and
change your alarm queries to use A2ALMDB.

OData Query Examples


Note: Use "%20" to indicate a space. Use "%27" to indicate a single quote.
If you are using the JSONView viewer in the Chrome browser, you can use a plus sign (+) to indicate a
space to make the URI string more readable.

The following query returns events after the specified dat e:

http://Server1:32569/Historian/v1/Events?$filter=EventTime+ge+datetimeoff
set%27014-08-10T05:56:21.302Z%27
The following query returns events for the proc ess variable named Flow3.PV:

184 Version 17.0.18000


Browser-Friendly Data Retrieval Wonderware Historian Retrieval Guide

http://Server1:32569/Historian/v1/Events?$filter=Source_ProcessVariable+e
q
+%27Flow3.PV%27+and+EventTime+ge+datetimeoffset%272014-08-10T05:56:21.302
Z%27
The following query returns events for a source area called "Site2":

http://Server1:32569/Historian/v1/Events?$filter=Source_Area+eq+%27Site2%
27+and+EventTime+ge+datetimeoffset%272014-08-10T05:56:21.302Z%27
The following query returns alarms that have returned to normal:

http://Server1:32569/Historian/v1/Events?$filter=Type+eq+%27Alarm.Clear%2
7
The following query returns alarms that have returned to normal and uses the $select option to ret urn
only a subset of the properties:

http://Server1:32569/Historian/v1/Events?$select=EventTime,Source_Area,So
urce_ProcessVariable,Comment&$filter=Type+eq+%27Alarm.Clear%27
The following query returns all events with an event time t hat is greater than or equal to the specified
time:

http://Server1:32569/Historian/v1/Events?$filter=EventTime+ge+datetimeoff
set%271970-01-01T00:00:00.000Z%27
The following query returns the first 10 events:

http://Server1:32569/Historian/v1/Events?$top=10&$filter=EventTime+ge+dat
etimeoffset%271970-01-01T00:00:00.000Z%27
The following query skips the first 10 events:

http://Server1:32569/Historian/v1/Events?$skip=10&$filter=EventTime+ge+da
tetimeoffset%271970-01-01T00:00:00.000Z%27

Summary History Query Options


Summary statistics are calculated for the Summary entity and the period-specific navigation properties
(for example, Hourly ). Depending on the tag type, the actual statistics are returned within the Analog,
Split, and Contained child properties.
Queries for summary history can include these additional query string parameters:

Child property Statistics returned

Analog Several of the values return selected, stored values rather than actual statistics.
These have associated timestamps (First, Last, Minimum, Maximum). The
actual statistics are all time-weighted.

Version 17.0.18000 185


Wonderware Historian Retrieval Guide Browser-Friendly Data Retrieval

Split or Contained The Split and Contained arrays include statistics on the amount of time (in
milliseconds) that the value spent in each state that occurred in the period.
Each array includes an element for each value encountered during that period.
If the value was "1" for the entire period queried, there is only one element; if
the value was "0", "1", and "2" in another period, the results for that period has
three rows.
For each array element, the statistics represent the amount of time the value
was in that state. For example, if you query an hour of data and the value was
"3" four times during that hour, for a total of 10 minutes, then the "A verage"
would be 150,000 milliseconds (2.5 minutes).

Using the Excel OData Feed to Import Process or Event Data


You use the Microsoft Excel ODat a Feed feature to import process or event dat a from the historian int o
an Excel spreadsheet.
To import data
1. Open an Excel spreadsheet.
2. On the Data tab, in the Get External Data group, click From Other Sources and select From
OData Data Feed. The Data Connection Wizard dialog box appears.

3. In the Location of the data feed section, enter the link for the OData Feed. Append the location
with the query option $format with a value of atom.
For example, you could append an on-premises location like this:

//localhost:32569/Historian/v2/Events?$format=atom

Note: To make the link more usable, you would also include a Date Time filter (see "Using Date
Time Filters" on page 182).

4. For Log on credentials, select the appropriate logon option and type the correct username and
password. The logon is valid until the Excel spreadsheet is closed.

186 Version 17.0.18000


Browser-Friendly Data Retrieval Wonderware Historian Retrieval Guide

5. Click Next. This Select Tables dialog box appears.

6. Select the appropriat e table. For events data, select the Events table.
7. Click Next. The Save Data Connection File and Finish dialog box appears.

8. Type a filename and description.


9. Click Finish. The Import Data dialog appears.

10. In the Select how you want to view this data in your workbook area, click Table.

Version 17.0.18000 187


Wonderware Historian Retrieval Guide Browser-Friendly Data Retrieval

11. In the Where do you want to put the data? area, specify if data goes to an existing or a new
worksheet.
12. Click OK. A static result set appears in the worksheet.

Querying History Blocks via SQL Server Reporting Services


Extension
Historian includes an extension for SQL Server Reporting Services to enable SQL queries against the
ODat a interface used for data stored in history blocks.
To configure the extension
1. Open the Configurat or.
2. Under Historian, click the Reporting node.
3. Select the versions of Visual Studio installed with your SQL Server Reporting Services.
4. Click Configure.
To use the extension
1. Define a new Reporting Services data source.
2. Select "Historian OData Provider" as the source type.
3. Click Historian and then click Extension.
4. Enter a connection string in the form "Server=host:port"; for example:

Server=localhost:32569
Three Ways To Query the Source
You can query the source using one of these options:
 Use a SQL-style query. For example:

select * from Events where Source_Area='Site2' and EventTime >=


'2014-08-10T05:56:21.302Z'
 Use an OData query. This OData query example is equivalent to the query above:

http://Server1:32569/Historian/v1/Events?$filter=Source_Area+eq+%27Sit
e2%27+and EventTime+ge+datetimeoffset%272014-08-10T05:56:21.302Z%27

Note: For queries from a web browser, use "%20" to indicate a space. Us e "%27" to indicate a
single quote.
If you are using the JSONView viewer in the Chrome browser, you can us e a plus sign (+) to
indicate a space to mak e the URI string more readable.

188 Version 17.0.18000


Browser-Friendly Data Retrieval Wonderware Historian Retrieval Guide

 Use an SQL syntax used within the URL. For example, this is equivalent to the other two queries
above:

http://Server1:32569/Historian/v1/Events?sql=select+*+from
Events+where
Source_Area=%27ite2%27+and+EventTime+>=+%272014-08-10T05:56:21.302Z%27

Supported OData Retrieval Syntax


The OData HTTP request is sent to the historian in this format:

<protocol>://<host>:<port>/<service_name>/7.8/<path>/<options>

Syntax component Description

Protocol Either http or https.


Host The URL of the historian from which you are retrieving data.
Port The port number for the historian. The default is "32569".
Service name Use "historian".
Version Version of the data (v1 or v2).OData interfaces can handle multiple
versions of the same data.
Path The path of the requested resource, such as "E vents" or
"ProcessValues". Or, you can use $metadata to find the list of all
resources in the system.
Options Other (non-required) system query options, which are prefixed with the
dollar sign ($).

Note: For process value and summary retrieval queries, the fully qualified
name is a mandatory filter value. The request will not work without it.

The default URLs for retrieving data through the OData interface are as follows:

 For process history:

http://<host>:<port>/Historian/v2/ProcessValues
 For event data:

http://<host>:<port>/Historian/v2/Events
Examples
This query lists all resources available for query on the server:

http://server1:32569/Historian/v1/$metadata
This query gets all events after August 1, 2016 at 6:15 p.m.:

http://server1:32569/Historian/v1/Events?$filter=EventTime+ge+2016-08-01T
18:15:00.000000Z

Version 17.0.18000 189


Wonderware Historian Retrieval Guide Browser-Friendly Data Retrieval

Note: Use "%20" to indicate a space. Use "%27" to indicate a single quote.
If you are using the JSONView viewer in the Chrome browser, you can use a plus sign (+) to indicate a
space to make the URI string more readable.

Each time you retrieve records, a maximum of 5,000 records is returned. For event ret rieval, only the
first 50 records for your query are returned by default. At the end of the last record, there is a link to the
next record set.
If you do not specify a time criteria in the query, then the last hour’s worth of data is returned by
default. If you specify time in your queries, use UTC. Fo r example:

2016-08-01T18:15:00.000000Z
If you use local time, be aware of UTC offset values in timezones that observe Daylight Savings Time.
For example, the following time specification would mean a 5-hour offset from UTC:

2014-07-4T23:00:0.000-5:00
However, the offset for time specification would need to be adjusted if Daylight Savings Time is in
effect:

2014-07-4T23:00:0.000-6:00
Records are always returned in UTC, regardless of any time offset included in the query.

Resources for OData Queries


To retrieve event data, specify a requested res ource of "E vents" in the OData query.
If the requested resource is empty (that is, the URI is the service root), the server returns the service
document that exposes the available collections of the web service.
If the resource is "$metadata", the server returns the Service Met adat a Document that exposes the
data model of the web service. Use the $metadata resource to find out the list of properties in the
system. For example:

http://server1:32569/Historian/v2/$metadata

190 Version 17.0.18000


Browser-Friendly Data Retrieval Wonderware Historian Retrieval Guide

Returns:

Supported Syntax Tokens and Operators


These tokens are supported for system query via iHistory. They are all case-sensitive.

Version 17.0.18000 191


Wonderware Historian Retrieval Guide Browser-Friendly Data Retrieval

Token Description

$filter Specifies an expression or function that must evaluat e to true for a record to be
returned in the collection.
All typical OData functions are supported for the $filter clause.
The $filter ex pression supports references to properties and literals. Literal values
include:
 Strings enclosed in single quotes
 Numbers and Boolean values (true or false)
Filtering for process value and summary data is case-sensitive.
However, while event property names are case-s ensitive, filtering is case-insensitive.
For example, if you filter property values based on a value of "true," values such as
"TRUE," "True," and "true" could be returned. The case returned in the query results
reflects the case of the stored value.

$select Specifies a subs et of properties to return.

$skip Specifies the number of records to skip from the beginning of the res ult set.

$skiptoken Used to get the next record set that satisfies the query conditions. You do not need to
include this token in the query, but you will see it upon query execution.

$top Specifies the maximum number of records to return. This subset is formed by
selecting only the first N items of the set, where N is a positive integer specified by
this query option.

These logical operat ors are supported for the query options:

Operator Description

eq Equal

ne Not equal

gt Greater than

ge Greater than or equal

lt Less than

le Less than or equal

and Logical and

or Logical or

not Logical negation

In the filter expression, you can only have a single time clause combined with a single filter clause
using the "and" operat or. The filter claus e itself can be complex, using any of the supported logical
operators. Use parentheses ( ) to creat e precedence groups within an expression in filter clause.

192 Version 17.0.18000


Browser-Friendly Data Retrieval Wonderware Historian Retrieval Guide

Note: Use "%20" to indicate a space. Use "%27" to indicate a single quote.
If you are using the JSONView viewer in the Chrome browser, you can use a plus sign (+) to indicate a
space to make the URI string more readable.

If the expression includes multiple values for the criteria, you must specify each criteria separately
using the "or" operator. For example:

...
((Priority+eq+100+or+Priority+eq+200+or+Priority+eq+500+or+Priority+eq+70
0)+and+(filter …))

When the filter clause is specified with E ventTime, where E vent Time Great erThan (or) GreaterThan
Equal, the E vent Time will be considered as the Start Time. E vent Time LessThan (or) Less ThanEqual
will be considered as EndTime. After considering the Start Time and EndTime, if any filter exists that
will be considered as First Filter, and there is no value if we specify OR (or) AND FilterOption for the
First Filter apart from the Start Time and EndTime.
The following queries both return the same res ult as using " and":

http://localhost:32569/Historian/v1/Events?$filter=EventTime+gt+datetimeo
ffset%272014-07-20T02:26:45%27+or+Priority+lt+900

http://localhost:32569/Historian/v1/Events?$filter=EventTime+gt+datetimeo
ffset%272014-07-20T02:26:45%27+and+Priority+lt+900

Resources
Historian Dat a RES T API exposes various resources through an endpoint URL that is specific to your
InSight solution.
This API includes the following res ourc es for retrieving data:
 Tags (see "Tags" on page 194)
 TagProperties (see "TagProperties" on page 195)
 TagPropertyV alues (see "TagP ropert yValues" on page 195)
 TagGroups (see "TagGroups" on page 195)
 TagSuggest (see "TagSuggest " on page 196)
 TagSearch (see "TagS earch " on page 196)
 TagE xtendedP roperties (see "TagE xtendedProperties" on page 197)
 ProcessValues (see "ProcessValues" on page 198)
 Daily (see "Daily" on page 199)
 Hourly (see "Hourly" on page 205)
 Minutely (see " Minutely" on page 206)
 SystemParameter (see "SystemP arameters" on page 198)

Note: All property names are case-sensitive. E vent storage preserves the case that you provide for
any property value. For example, a property value of " TRUE" is different than "True" and "true."

Version 17.0.18000 193


Wonderware Historian Retrieval Guide Browser-Friendly Data Retrieval

Tags
The Tags resource retrieves tag metadata. For version 2, this also includes tag extended properties.

Property Data Type Description

FNQ* String The fully qualified name for the tag. A fully qualified tagname
uses the format: Dat aSourceName. TagName.
Source String The data source.

Description String The description of the tag.

EngUnit String The engineering units used for the tag's rec orded values.

EngUnitMax Double The maximum value of the tag, measured in engineering


units.
EngUnitMin Double The minimum value of the tag, measured in engineering units.

InterpolationTy pe String The interpolation type for retrieval. 0 = Stair-stepped


interpolation; 1 = Linear interpolation (if applicable, based on
the tag type); 254 = System default interpolation mode. The
system default interpolation type is to use the system default
for the analog type, either integer or real. The system default
interpolation type for an analog type is determined by the
setting of the InterpolationTypeInteger and
InterpolationTy peReal system paramet ers. This setting
impacts Interpolated, A verage, and Integral retrieval modes.
IntegralDivisor Double The factor to be applied when integrating a rat e with the units
[EngUnits/ TimeUnit] to a quantity with units [EngUnits]. This
factor is called the integral divisor.
The default value of 1 assumes a time unit of seconds and
ensures that a rate of [Unit/second] is correctly integrated to
[Unit].
For a time unit of minutes, set the integral divisor value to 60;
for a unit of hours, set the integral divis or value to 3600. The
integral divis or is applied similarly to rates or quantities that
are not expressed in terms of a time unit. For example, to
convert watts to watt-hours, the integral divisor is 1/3600. To
convert watts to kilowatt-hours, the integral divisor is
1/3600000. Internal use only.
RolloverValue Double The rollover value for the tag.

MessageOff String The message associated with the FALSE state of the discrete
tag. The maximum number of characters is 64. A discrete tag
set to 0 is in the FALSE state.
MessageOn String The message associated with the TRUE state of the discrete
tag. The maximum number of characters is 64. A discrete tag
set to 1 is in the TRUE state.
TagName String The unique name of the tag wit hin the Wonderware Historian
system.

194 Version 17.0.18000


Browser-Friendly Data Retrieval Wonderware Historian Retrieval Guide

Property Data Type Description

TagType String The type of tag. 1 = Analog; 2 = Discrete; 3 = String; 5 =


E vent, 7 = Summary tag (analog or state). TagType is a
foreign key from the Wonderware Historian TagRef table.
Raw Identifies related the raw ac quired value.

Minutely Identifies related minutely summary.

Hourly Identifies related hourly summary.

Daily Identifies related daily summary.

* Required property.

TagProperties
The TagProperties resource lists all properties used in the system. Tag properties include both base
and extended properties of a tag.
Examples of TagProperties are DataSourceName and Unit.

Property Data Type Description

Name* String The unique name of the tag property.

Values Valid values for this property.

* Required property.

TagPropertyValues
The TagPropertyValues res ource retrieves values for one or more tag properties. Tag properties
include base and extended properties of Tag. Examples of TagProperties are DataS ourceName and
Unit.

Property Data Type Description

Name* String Unique name of the tag property value.

Value* String

Tags Identifies related Tags.

* Required property.

TagGroups
The TagGroup resource retrieves information about data sources. Each dat a source contains a group
of tags.

Version 17.0.18000 195


Wonderware Historian Retrieval Guide Browser-Friendly Data Retrieval

Property Data Type Description

GroupID* String Globally unique identifier for the tag group.

GroupName String The name of the data sourc e.

TypeID String The type of data source.

ParentID String

Scope String Used for tag-level security, this defines a location within the
data source.
Tags Identifies related Tags.

Groups Identifies related TagGroups.

* Required property.

TagSuggest
The TagSuggest resource provides search suggestions in response to user input. The data ret urned by
this entity depends on the historian’s implementation of searc h functionality. Some historians will return
empty result sets.
It finds all the matching results for a given query string. It searches for the matching rec ord based on all
the searchable fields in the search index; such as, source, tagname, description, and engineering unit.
The results contain the matching field name, value, hit count, and search ranking.
The query option "q" specifies the query string (for example, the value typed by the user int o the
search box).
For example:
http://localhost/Historian/v2/TagSuggest?q=r&$top=100

Property Data Type Description

Value* String The suggested value.

FieldName String The related field name.

Count Double The hit count for this query string.

SearchRanking Double The search ranking for the tag.

Display Text String The associated display text.

Search

Tags Identifies related Tags.

ExpandS uggest

* Required property.

TagSearch
The TagSearch resourc e provides tagname results based on provided searc h paramet ers.

196 Version 17.0.18000


Browser-Friendly Data Retrieval Wonderware Historian Retrieval Guide

The data returned by this entity is dependent on the historian’s implementation of search functionality.
Some historians will ret urn empty result sets.
It finds all the matching results for a given query string. It is basically used to filter the results based on
the suggestion results. It searches for the matching record only on the fields provided in the key name
as part of the query parameter. The results contain basic tag metadata information; such as FQN,
tagname, source, and search ranking.
You can use thes e query options:
 q - Specifies the query string (for example, the value typed by the user into the search box).
 kn - Specifies the key name (field name) to which the search will be applied.
 kv - S pecifies the key value which will be used for the search.
For example:

http://localhost/Historian/v2/TagSearch?q=r&kn=source&kv=atron

Property Data Type Description

FQN* String The fully qualified name for the tag. A fully qualified tagname
uses the format: Dat aSourceName. TagName.
Source String The data source.

TagName String The name of the tag.

Display Text String The displayed text for the tag.

SearchRanking Double The search ranking for this tag.

Tag Returns a URL to retrieve a list of Tag entity values for the
tags that match.
* Required property.

TagExtendedProperties
The TagExtendedProperties res ource represents all the Tag properties, including both standard and
extended properties.

Property Data Type Description

FQN* String The fully qualified name for the tag. A fully qualified tagname
uses the format: Dat aSourceName. TagName.
PropertyName* String The name of the property.

Value Double The value of the property.

Text String The associated text for the property.

Version 17.0.18000 197


Wonderware Historian Retrieval Guide Browser-Friendly Data Retrieval

Property Data Type Description

Type String Can be one of these:


 [Edm.]String
 [Edm.]Int16, Int32, Int64
 [Edm.]Double
 [Edm.]DateTimeOffset
 [Edm.]Guid
 [Edm.]Boolean
 [Edm.]Geography types
 [Edm.]Geometry types
* Required property.

ProcessValues
The Proc essValues resource retrieves a set of process history values.

Property Data Type Description

FQN* String The fully qualified name for the tag. A fully qualified tagname
uses the format: Dat aSourceName. TagName.
DateTime* DateTimeOffset DateTime (Edm. DateTimeOffset) is always specified in UTC
using the RFC3339 / ISO8601 format with the Z time zone
designator. For example: 2016-09-03T18: 44:09.352247Z
OPCQuality Int32 The data quality as reported by the source.

Value Double 0 or 1 .

Text String Cont ain the value for a string tag or message associated with
Discrete Tags, while Value will contain 0 or 1.
* Required property

SystemParameters
(On-premises Wonderware Historian InSight only)
The SystemParameters resource retrieves names and values for system parameters.

Property Data Type Description

Name* String Unique name for the system parameter.

Value String The value of this system parameter.

Tags Identifies related tags.

* Required property.

198 Version 17.0.18000


Browser-Friendly Data Retrieval Wonderware Historian Retrieval Guide

Summary Resources
The Summary history data dictionary includes these structures:
 DailySummary (see "Daily" on page 199)
 HourlySummary (see "Hourly" on page 205)
 MinutelySummary (see " Minutely" on page 206)

Note: All property names are case-sensitive. E vent storage preserves the case that you provide for
any property value. For example, a property value of " TRUE" is different than "True" and "true."

Summary Structure
The Summary structure represent summary data with a user-defined interval.
The additional query option "Res olution" is used to specify the interval to be used for this entity.
The earliest and latest requested values of StartDateTime and/or EndDateTime are used for
determining the span of time covered by the summary intervals returned.

Property Name Data Type Description

FQN* String The fully qualified name for the tag.

StartDateTime* DateTime Start of the timeframe reported.


Offset
EndDateTime* DateTime End of the timeframe reported.
Offset
OPCQuality Double

PercentGood Double

Analog Analog
Statistics
Split Collection
(State
Statistics)
Cont ained Collection
(State
Statistics)
Raw

* Required property.

Daily
The Daily resource retrieves daily (24-hour resolution) summary values for the tags specified. The
default for Daily is to report summary values for the last week.

Version 17.0.18000 199


Wonderware Historian Retrieval Guide Browser-Friendly Data Retrieval

Property Data Type Description

FQN* String The fully qualified name for the tag. A fully qualified tagname
uses the format: Dat aSourceName. TagName.
StartDateTime* DateTime Start of the timeframe reported.
Offset
EndDateTime* DateTime End of the timeframe reported.
Offset
TimeZone String The timezone used for the timeframe. See "Accepted values
for TimeZone" below.
OPCQuality Double OPC quality. Normal OPC quality retrieval logic is applied if:
All the point found and processed for this row have GOOD
quality. If they all have the same GOOD quality, then that
quality is returned.
If there is a gap in the entire calculation cycle, then BAD
quality is returned for the tag.
For any other scenario with any mixture of GOOD and BAD
points, a DOUB TFUL OP C quality (64) is returned.
PercentGood Double The ratio of the number of rows that have "good" quality to
the total number of rows in the retrieval cycle, expressed as a
percentage in the range 0 to 100.
Analog Analog An embedded collection that maps to AnalogSummary.
Statistics
Split Collection An embedded collection that maps to StateSummary for the
(State ValueState retrieval mode.
Statistics)
Cont ained Collection An embedded collection that maps to StateSummary for the
(State Cont ainedState retrieval mode.
Statistics)
Raw A URL us ed to retrieve all stored values for a specified time
period and tag. This is equivalent to a preconfigured
ProcessValue (s ee "ProcessValues" on page 198) query.
Minute

Hourly

* Required property.
Accepted values for TimeZone

UTC offset in minute s TimeZone value

0 UTC

0 Morocco Standard Time

0 GMT Standard Time

200 Version 17.0.18000


Browser-Friendly Data Retrieval Wonderware Historian Retrieval Guide

0 Greenwich Standard Time

60 W. Europe Standard Time

60 Cent ral Europe Standard Time

60 Romance Standard Time

60 Cent ral European Standard Time

60 W. Central Africa Standard Time

60 Namibia Standard Time

120 Jordan Standard Time

120 GTB Standard Time

120 Middle East Standard Time

120 Egypt Standard Time

120 E. Europe Standard Time

120 Syria Standard Time

120 West Bank Standard Time

120 South Africa Standard Time

120 FLE Standard Time

120 Israel Standard Time

120 Kaliningrad Standard Time

120 Libya Standard Time

180 Arabic Standard Time

180 Turkey Standard Time

180 Arab Standard Time

180 Belarus Standard Time

180 Russian Standard Time

180 E. Africa Standard Time

210 Iran Standard Time

240 Arabian Standard Time

240 Astrakhan Standard Time

240 Azerbaijan Standard Time

240 Russia Time Zone 3

240 Mauritius Standard Time

Version 17.0.18000 201


Wonderware Historian Retrieval Guide Browser-Friendly Data Retrieval

240 Georgian Standard Time

240 Cauc asus Standard Time

270 Afghanistan Standard Time

300 West Asia Standard Time

300 Ekaterinburg Standard Time

300 Pakistan Standard Time

330 India Standard Time

330 Sri Lanka Standard Time

345 Nepal Standard Time

360 Cent ral Asia Standard Time

360 Bangladesh Standard Time

360 Omsk Standard Time

390 Myanmar Standard Time

420 SE Asia Standard Time

420 Altai Standard Time

420 W. Mongolia Standard Time

420 Nort h Asia Standard Time

420 N. Central Asia Standard Time

420 Tomsk Standard Time

480 China Standard Time

480 Nort h Asia East Standard Time

480 Singapore Standard Time

480 W. Australia Standard Time

480 Taipei Standard Time

480 Ulaanbaatar Standard Time

510 Nort h Korea Standard Time

525 Aus Central W. Standard Time

540 Trans baikal Standard Time

540 Tokyo Standard Time

540 Korea Standard Time

540 Yakutsk Standard Time

570 Cen. Australia Standard Time

202 Version 17.0.18000


Browser-Friendly Data Retrieval Wonderware Historian Retrieval Guide

570 AUS Central Standard Time

600 E. Australia Standard Time

600 AUS Eastern Standard Time

600 West Pacific Standard Time

600 Tasmania Standard Time

600 Vladivostok Standard Time

630 Lord Howe Standard Time

660 Bougainville Standard Time

660 Russia Time Zone 10

660 Magadan Standard Time

660 Norfolk Standard Time

660 Sakhalin Standard Time

660 Cent ral Pacific Standard Time

720 Russia Time Zone 11

720 New Zealand Standard Time

720 UTC+ 12

720 Fiji Standard Time

720 Kamchatka Standard Time

765 Chat ham Islands Standard Time

780 Tonga Standard Time

780 Samoa Standard Time

840 Line Islands Standard Time

-60 Azores Standard Time

-60 Cape Verde Standard Time

-120 UTC-02

-120 Mid-Atlantic Standard Time

-180 Tocantins Standard Time

-180 E. South America Standard Time

-180 SA Eastern Standard Time

-180 Argentina Standard Time

-180 Greenland Standard Time

-180 Montevideo Standard Time

Version 17.0.18000 203


Wonderware Historian Retrieval Guide Browser-Friendly Data Retrieval

-180 Saint Pierre Standard Time

-180 Bahia Standard Time

-210 Newfoundland Standard Time

-240 Paraguay Standard Time

-240 Atlantic Standard Time

-240 Venezuela Standard Time

-240 Cent ral Brazilian Standard Time

-240 SA Western Standard Time

-240 Pacific SA Standard Time

-240 Turks And Caicos Standard Time

-300 SA Pacific Standard Time

-300 Eastern Standard Time (Mexico)

-300 Eastern Standard Time

-300 Haiti Standard Time

-300 Cuba Standard Time

-300 US Eastern Standard Time

-360 Cent ral America Standard Time

-360 Cent ral Standard Time

-360 Easter Island Standard Time

-360 Cent ral Standard Time (Mexico)

-360 Canada Central Standard Time

-420 US Mountain Standard Time

-420 Mountain Standard Time (Mexico)

-420 Mountain Standard Time

-480 Pacific Standard Time (Mexico)

-480 UTC-08

-480 Pacific Standard Time

-540 Alaskan Standard Time

-540 UTC-09

-570 Marquesas Standard Time

-600 Aleutian Standard Time

-600 Hawaiian Standard Time

204 Version 17.0.18000


Browser-Friendly Data Retrieval Wonderware Historian Retrieval Guide

-660 UTC-11

-720 Dateline Standard Time

Hourly
The Hourly resource ret rieves hourly summary values for the tags specified. The default for Hourly is to
report summary values for the last 24 hours.

Property Data Type Description

FQN* String The fully qualified name for the tag. A fully qualified tagname
uses the format: Dat aSourceName. TagName.
StartDateTime* DateTime Start of the timeframe reported.
Offset
EndDateTime* DateTime End of the timeframe reported.
Offset
OPCQuality Double OPC quality. Normal OPC quality retrieval logic is applied if:
All the point found and processed for this row have GOOD
quality. If they all have the same GOOD quality, then that
quality is returned.
If there is a gap in the entire calculation cycle, then BAD
quality is returned for the tag.
For any other scenario with any mixture of GOOD and BAD
points, a DOUB TFUL OP C quality (64) is returned.
PercentGood Double The ratio of the number of rows that have "good" quality to
the total number of rows in the retrieval cycle, expressed as a
percentage in the range 0 to 100.
Analog Analog An embedded collection that maps to AnalogSummary.
Statistics
Split Collection An embedded collection that maps to StateSummary for the
(State ValueState retrieval mode.
Statistics)
Cont ained Collection An embedded collection that maps to StateSummary for the
(State Cont ainedState retrieval mode.
Statistics)
Raw A URL us ed to retrieve all stored values for a specified time
period and tag. This is equivalent to a preconfigured
ProcessValue (s ee "ProcessValues" on page 198) query.
Minute

* Required property.

Version 17.0.18000 205


Wonderware Historian Retrieval Guide Browser-Friendly Data Retrieval

Minutely
The Minutely resource retrieves summary values with a 1 -minute resolution for the tags specified.
Default duration for minutely summaries is the last 1 hour. The default for Minut ely is to report
summary values for the last hour.

Property Data Type Description

FQN* String The fully qualified name for the tag. A fully qualified tagname
uses the format: Dat aSourceName. TagName.
StartDateTime* DateTime Start of the timeframe reported.
Offset
EndDateTime* DateTime End of the timeframe reported.
Offset
OPCQuality Double OPC quality. Normal OPC quality retrieval logic is applied if:
All the point found and processed for this row have GOOD
quality. If they all have the same GOOD quality, then that
quality is returned.
If there is a gap in the entire calculation cycle, then BAD
quality is returned for the tag.
For any other scenario with any mixture of GOOD and BAD
points, a DOUB TFUL OP C quality (64) is returned.
PercentGood Double The ratio of the number of rows that have "good" quality to
the total number of rows in the retrieval cycle, expressed as a
percentage in the range 0 to 100.
Analog Analog An embedded collection that maps to AnalogSummary.
Statistics
Split Collection An embedded collection that maps to StateSummary for the
(State ValueState retrieval mode.
Statistics)
Cont ained Collection An embedded collection that maps to StateSummary for the
(State Cont ainedState retrieval mode.
Statistics)
Raw A URL us ed to retrieve all stored values for a specified time
period and tag. This is equivalent to a preconfigured
ProcessValue (s ee "ProcessValues" on page 198) query.
* Required property.

Event Resources
The Historian Data REST AP I includes the following resources for retrieving data:
 Event Data Structure on page 207
 Provider Dat a Structure on page 207
 User Data Structure on page 208
 Source Data Structure on page 208

206 Version 17.0.18000


Browser-Friendly Data Retrieval Wonderware Historian Retrieval Guide

 Alarm Data Structure on page 209


 Verifier Data Structure on page 210

Note: All property names are case-sensitive. E vent storage preserves the case that you provide for
any property value. For example, a property value of " TRUE" is different than "True" and "true."

Event Data Structure


The E vent Data structure is the top-level container for all events. It contains its own properties, as well
as the other data structures (Source, User, Provider, and so on).

Property Name Data Type Description

ID* GUID Globally unique identifier for the event.

Priority Int32 Value indicating the import ance of the event. Values range
from 1 to 999, with lower numbers indicating higher
importance.

Severity Int32 Categoriz ation of the urgency of the event:


1 - Critical
2 - Major
3 - Minor
4 - Informational

Type* String Main categorization of the event. Examples include


"Alarm.Set", "Engine.Start", and "User.Write", among ot hers.

E vent Time DateTime UTC timestamp indicating when the event occurred.

ReceivedTime DateTime UTC timestamp indicating when the event was received by
the Historian server.

IsAlarm Bool "true" or "false" indicating whether this event is an alarm.

Comment String A comment providing more information about the event.

Note: If an alarm comment from Application Server contains


a backslash (for example, \n), then an extra backslash
appears in the event res ult (for example, \\n) in the browser.

InTouchType String InTouch Type value. Examples include "ALM", "RTN", "ACK",
and "SYS", among ot hers.

* Required property.

Provider Data Structure


The Provider Data structure is contained within the top -level E vent Data Structure.

Version 17.0.18000 207


Wonderware Historian Retrieval Guide Browser-Friendly Data Retrieval

Data
Property Name Type Description

Provider_NodeName String Name of the node that generated the event.

Provider_System String Software system that generated the event. Examples


include "Application Server", "InTouch", and " InBatch".

Provider_ApplicationName String Application that generat ed the event. For Application


Server, this will be the galaxy name. For InTouch, it will
be the InTouch application name.

Provider_SystemVersion String Software version (for example, 4566.1210.5811.1) for


the component identified by Provider_ApplicationName.

Provider_Instanc eName String Provider-specific string that uniquely identifies the


instance an application on a given node.

User Data Structure


The User Data structure is contained within the top-level E vent Data Structure.

Data
Property Name Type Description

User_Account String This is the login name for the operator for the given application.

User_Name String Name of the user.

User_NodeName String Computer name from which a user action was executed.

User_Agent String Application name that the user was running when the event was
generated.

Source Data Structure


The Source Data structure is contained within the top-level E vent Data Structure.

Data
Property Name Type Description

Source_Proc essVariable String Process variable to which the event is related.

Source_Units String Engineering units used for the process variable.

Source_ConditionVariable String Condition variable related to the event. For example, if


"TIC101" has a field attribute "PV" and this is a "Hi"
alarm, this value will be "TIC101.PV.Hi".

Source_Object String Non-hierarchical name for the object to which the event
is related, for example, " TIC101".

208 Version 17.0.18000


Browser-Friendly Data Retrieval Wonderware Historian Retrieval Guide

Data
Property Name Type Description

Source_HierarchicalObject String Hierarchical name for the source object. For example,
"Reactor_001. TIC".

Source_Area String Non-hierarchical Area name. For example, "Area_001".

Source_HierarchicalArea String Hierarchical Area name. For example,


"Plant_001.Building_002.Mixing".

Source_Engine String Non-hierarchical engine name. For example,


"AppEngine_001".

Source_Platform String Non-hierarchical platform name. For example


"WinPlatform_001".

Alarm Data Structure


The Alarm Data structure is contained within the top -level E vent Data Structure.

Data
Property Name Type Description

Alarm_ID String ID of the original Alarm event. For "Alarm.Set" events, this
will be the same as the event ID.

Alarm_Class String InTouch alarm classification. Examples include "DSC"


(discrete), "VALUE" (LoLo, Hi, etc.), "DEV" (deviation), and
"ROC" (rate of change).

Alarm_Type String InTouch alarm type.

Alarm_InAlarm Boolean "true" or "false" indicating whether the Alarm is still in the
active state.

Alarm_State String State of the alarm. Possible values are "UNA CK_ALM",
"UNA CK_RTN", "ACK_ALM", and "ACK_RTN".

Alarm_TagType String Types of tags associated with the alarm.

Alarm_Acknowledged Boolean "true" or "false" indicating whether the user has


acknowledged this alarm.

Alarm_Condition String The condition being alarmed. Examples include "Limit.Hi",


"ROC. Lo", and "System" among others.

ValueString String Value logged for the variable related to the event.

Alarm_LimitString String Limit being alarmed.

Version 17.0.18000 209


Wonderware Historian Retrieval Guide Browser-Friendly Data Retrieval

Data
Property Name Type Description

Alarm_UnAckDurationMs Int32 The duration, in milliseconds, for which the alarm went
un-acknowledged.

Alarm_DurationMs Int32 The duration, in milliseconds, for which the alarm was
active.

Alarm_IsSilenced Boolean "true" or "false" indicating whether the alarm was silenced.

Alarm_IsShelved Boolean "true" or "false" indicating whether the alarm was shelved.

Alarm_S helveStartTime Date Scheduled start of the shelve time if the alarm has been
Time shelved.

Alarm_S helveDurationMs Int32 The duration, in milliseconds, for which the alarm was
shelved.

Alarm_S helveReason String The reason the alarm was shelved.

Alarm_OriginationTime Date Provides the time of the initial alarm condition, so that it can
Time be ret rieved quickly.

Verifier Data Structure


The Verifier Data structure is contained within the top-level E vent Data Structure and is populated for a
verified write operation.

Property Name Data Type Description

Verifier_Account String The login name for the verifier of a verified write operation.

Verifier_Name String First and last name of the verifier of a verified write operation.

Verifier_NodeName String Computer name from which a user write was verified.

Verifier_Agent String Name of the application the verifier of a user write was running.

Flexible Properties
If an event is generated with a property that is not handled by the defined dat a dictionary, then that
property is considered a flexible property. These flexible properties appear in the result set with a
property name of "Properties."
The following are JSON examples of an event with flexible properties, which are named "property1"
and "property2".

210 Version 17.0.18000


Browser-Friendly Data Retrieval Wonderware Historian Retrieval Guide

{
"odata.metadata":"http://localhost:32569/Historian/$metadata#Events","value":[
{
"Comment":"DisplayText","EventTime":"2014-09-02T16:03:12Z","ID":"1d9b9518-
b1ca-4270-a189-e43cc258645f","Priority":708,"ReceivedTime":"0001-01-01T00:
00:00Z","IsAlarm":false,"Severity":3,"Type":"EventType1","Provider_NodeNam
e":"RM00155948","Provider_System":"System1","Source_ProcessVariable":"Sour
ce1","Source_Area":"Area1","Alarm_IsSilenced":false,"Properties":[
{
"Name":"property1","Value":"QZIKFGN"
},{
"Name":"property2","Value":"8982922"
}
]
},{
"Comment":"DisplayText","EventTime":"2014-09-03T01:16:22Z","ID":"2aae8e30-
72ae-4839-b7ff-c1a2ec7f4cc5","Priority":566,"ReceivedTime":"0001-01-01T00:
00:00Z","IsAlarm":true,"Severity":2,"Type":"EventType1","Provider_NodeName
":"RM00155948","Provider_System":"System1","Source_ProcessVariable":"Sourc
e1","Source_Area":"Area1","Alarm_ID":"a4a8bb5c-cc96-4bdd-b266-81a566c4c4bc
","Alarm_Class":"ALMC","Alarm_Type":"ALMTYP","Alarm_IsSilenced":false,"Ala
rm_State":"ALMSTATE","Properties":[
{
"Name":"property1","Value":"IRFMOGF"
},{
"Name":"property2","Value":"5105479"
}
]
},{
"Comment":"DisplayText","EventTime":"2014-09-03T04:09:16Z","ID":"4047bb01-
dc4b-4b25-99e0-399d2c6a38af","Priority":785,"ReceivedTime":"0001-01-01T00:
00:00Z","IsAlarm":false,"Severity":2,"Type":"EventType1","Provider_NodeNam
e":"RM00155948","Provider_System":"System1","Source_ProcessVariable":"Sour
ce1","Source_Area":"Area1","Alarm_IsSilenced":false,"Properties":[
{
"Name":"property1","Value":"DBDPGDV"
},{
"Name":"property2","Value":"7680935"
}
]
}
],"odata.nextLink":"http://localhost:32569/Historian/Events?$top=3&$filter=Event
Time%20ge%20datetimeoffset%272014-09-01T16%3A28%3A20.0000000Z%27%20and%20%27prop
erty1%27%20ne%20%270%27&$skiptoken=2014-09-03T04:09:16.0000000Z%7C4047bb01-dc4b-
4b25-99e0-399d2c6a38af"
}

Errors
The OData error codes listed in the following table may be returned by an operation on any of the
storage services.

Version 17.0.18000 211


Wonderware Historian Retrieval Guide Browser-Friendly Data Retrieval

Error code HTTP status code User message

ConditionNotMet Not Modified (304) The condition specified in the


conditional header(s ) was not met for
a read operation.

MissingRequiredQueryParamet er Bad Request (400) A required query parameter was not


specified for this request.

UnsupportedQueryParamet er Bad Request (400) One of the query parameters


specified in the request URI is not
supported.

InvalidQueryParameterValue Bad Request (400) An invalid value was specified for one
of the query paramet ers in the
request URI.

OutOfRangeQueryParameterV alue Bad Request (400) A query parameter specified in the


request URI is outside the permissible
range.

RequestUrlFailedToParse Bad Request (400) The url in the request could not be
parsed.

InvalidUri Bad Request (400) The requested URI does not


represent any resource on the server.

InvalidHttpVerb Bad Request (400) The HTTP verb specified was not
recognized by the server.

OutOfRangeInput Bad Request (400) One of the request inputs is out of


range.

InvalidAuthenticationInfo Bad Request (400) The authentication information was


not provided in the correct format.
Verify the value of
Authorizationheader.

InvalidInput Bad Request (400) One of the request inputs is not valid.

Unauthorized Unauthorized (401) Unauthorized: Access is denied due


to invalid credentials.

ResourceNotFound Not Found (404) The specified resource does not exist.

InternalError Internal Server E rror The server encountered an internal


(500) error. Please retry the request.

212 Version 17.0.18000


Browser-Friendly Data Retrieval Wonderware Historian Retrieval Guide

Error code HTTP status code User message

OperationTimedOut Internal Server E rror The operation could not be complet ed


(500) within the permitted time.

ServerB usy Service Unavailable The server is currently unable to


(503) receive requests. Please retry your
request.

Version 17.0.18000 213

You might also like