开发者

Averages in Sql Server Management Studio

I need to get daily averages for several tags in my data. I am running into a problem with the following query that I have set up:

SET NOCOUNT ON
DECLARE @StartDate DateTime
SET @StartDate = '20100101 00:00:00.000'
SET NOCOUNT OFF
SELECT TagName, DateTime, avg(Value), avg(vValue)
FROM History
WHERE TagName IN ('BFC_CGA_PE.qAr_Reading', 'BFC_CGA_PE.qBTU_Avg', 'BFC_CGA_PE.qBTU_Calc', 'BFC_CGA_PE.qCH4_Reading', 'BFC_CGA_PE.qCO_Reading', 'BFC_CGA_PE.qCO2_Reading', 'BFC_CGA_PE开发者_如何学Python.qH2_Reading', 'BFC_CGA_PE.qN2_Reading', 'BFC_CGA_PE.qO2_Reading')
AND wwRetrievalMode = 'Cyclic' 
AND wwVersion = 'Latest'
AND DateTime >= @StartDate

The error that I receive after my attempt to execute is: Msg 8120, Level 16, State 1, Line 5 Column 'History.TagName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Could someone help to develop a query to fetch daily average values for my tags?


Try this: (GROUP BY clause added and DateTime column removed from query)

SELECT TagName, /*DateTime,*/ avg(Value), avg(vValue)
FROM History
WHERE TagName IN ('BFC_CGA_PE.qAr_Reading', 'BFC_CGA_PE.qBTU_Avg', 'BFC_CGA_PE.qBTU_Calc', 'BFC_CGA_PE.qCH4_Reading', 'BFC_CGA_PE.qCO_Reading', 'BFC_CGA_PE.qCO2_Reading', 'BFC_CGA_PE.qH2_Reading', 'BFC_CGA_PE.qN2_Reading', 'BFC_CGA_PE.qO2_Reading')
AND wwRetrievalMode = 'Cyclic' 
AND wwVersion = 'Latest'
AND DateTime >= @StartDate
GROUP BY TagName
ORDER BY TagName

You just need a group by for TagName. Notice I removed your DateTime column for now. Date time values are likely to be unique and therefore not good candidates for aggregation. Not without some work to isolate a section of the data time value.


Add a GROUP BY clause. Also assuming the DateTime field is storing a date and time, you will want to aggregate by date alone to get daily average as in query below:

SELECT 
  TagName, 
  DATEADD(D, 0, DATEDIFF(D, 0, DateTime)), 
  avg(Value), 
  avg(vValue)
FROM History
WHERE TagName IN ('BFC_CGA_PE.qAr_Reading', 'BFC_CGA_PE.qBTU_Avg', 'BFC_CGA_PE.qBTU_Calc', 'BFC_CGA_PE.qCH4_Reading', 'BFC_CGA_PE.qCO_Reading', 'BFC_CGA_PE.qCO2_Reading', 'BFC_CGA_PE.qH2_Reading', 'BFC_CGA_PE.qN2_Reading', 'BFC_CGA_PE.qO2_Reading')
AND wwRetrievalMode = 'Cyclic' 
AND wwVersion = 'Latest'
AND DateTime >= @StartDate
GROUP BY TagName, DATEADD(D, 0, DATEDIFF(D, 0, DateTime)) 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜