设置AVG结果AS列

时间:2011-07-13 16:48:43

标签: sql sql-server sql-server-2005

我正在SQL Server 2005中运行查询。查询需要有一个整列由相同数字组成的列。该数字是查询中另一行的平均值。这就是我所拥有的,也许它将有助于理解我正在尝试的东西。此数据具有“颜色”值,并且“DataExtraLineValue”与整个向下相同,因为读取此查询的软件正在吐出图表。基本上,为什么我不能运行AVG(TagValueInteger)AS DataExtraLineValue

SELECT
      RecordedDateTime AS DataGroup,
      TagValueInteger AS DataBar,
      TagValueInteger AS DataLine,
      'Green' AS DataColor,
      'Avg' AS DataExtraLineLabel,
       AVG(TagValueInteger) AS DataExtraLineValue,
      'Blue' AS DataExtraLineColor
FROM tTagHistory
WHERE
      (TagHistoryDefinitionID = 2) AND
      (IsQualityGood = 1) AND
      (DeltaValueInteger <> 0) AND
      (TagValue > 4) AND
      (TagValue < 60) AND 
      (RecordedDateTime > (GetDate()-2))
ORDER BY RecordedDateTime DESC

3 个答案:

答案 0 :(得分:4)

你不能这样做,因为没有分组。如果没有分组,您的AVG将成为每行的值。如果您想要整个表的该字段的所有值的平均值,您可以将其设为子查询:

SELECT ....
       (SELECT AVG(TagValueInteger) FROM tTagHistory) as DataExtraLineValue
       ....

答案 1 :(得分:1)

另一种方法就是这样:

SELECT 
  ....    
  AVG(TagValueInteger) over () AS DataExtraLineValue
  ....

答案 2 :(得分:1)

AVG是一个聚合函数。使用聚合函数意味着分组。您可以聚合整个行集或组中的值。在前一种情况下,您不能拥有非聚合列(静态值除外,如'Green''Avg'个),在后一种情况下,您必须引入GROUP BY子句列出您要列出的内容定义组的所有列:这些列将在SELECT列表中进行非聚合。由于您的查询确实有一些非聚合值,因此更有可能是第二种情况,您的查询应该看起来像这样:

SELECT
      RecordedDateTime AS DataGroup,
      TagValueInteger AS DataBar,
      TagValueInteger AS DataLine,
      'Green' AS DataColor,
      'Avg' AS DataExtraLineLabel,
       AVG(TagValueInteger) AS DataExtraLineValue,
      'Blue' AS DataExtraLineColor
FROM tTagHistory
WHERE
      (TagHistoryDefinitionID = 2) AND
      (IsQualityGood = 1) AND
      (DeltaValueInteger <> 0) AND
      (TagValue > 4) AND
      (TagValue < 60) AND 
      (RecordedDateTime > (GetDate()-2))
GROUP BY RecordedDateTime, TagValueInteger
ORDER BY RecordedDateTime DESC

但是,根据您的帖子,您更有可能要检索聚合值和非聚合值。在这种情况下,您需要窗口聚合。通过向其添加OVER clause,聚合函数将成为窗口聚合函数。在你的特殊情况下,它应该是这样的:

SELECT
      RecordedDateTime AS DataGroup,
      TagValueInteger AS DataBar,
      TagValueInteger AS DataLine,
      'Green' AS DataColor,
      'Avg' AS DataExtraLineLabel,
       AVG(TagValueInteger) OVER () AS DataExtraLineValue,
      'Blue' AS DataExtraLineColor
FROM tTagHistory
WHERE
      (TagHistoryDefinitionID = 2) AND
      (IsQualityGood = 1) AND
      (DeltaValueInteger <> 0) AND
      (TagValue > 4) AND
      (TagValue < 60) AND 
      (RecordedDateTime > (GetDate()-2))
ORDER BY RecordedDateTime DESC

AVG(TagValueInteger) OVER ()返回整个行集的TagValueInteger的平均值。或者,您可以修改OVER ()子句,以便为每个不同的组返回不同(可能重复)的值,例如`AVG(TagValueInteger) OVER (PARTITION BY DataGroup)将为DataGroup的不同值返回不同的平均值。您可以在链接的文章中阅读更多相关信息。