查找前30个结果的平均值

时间:2015-06-16 13:08:34

标签: sql-server average

我有一个输出前30个结果的查询

select top 30 * from [dbo].[Stats]
        where Rack_Code = 'ABC'
        order by Date_of_Record desc

并查询以获取所有时间的平均值

SELECT AVG(Total_MB - (East_MB + West_MB)) AS Other,
                    AVG(East_MB) AS East,
                    AVG(West_MB) AS West
                    FROM [dbo].[Stats]
                    WHERE Rack_Code = 'ABC'

提供正确的输出

enter image description here

但是当我尝试获得前30个条目的平均值时,SQL查询似乎忽略了Top 30

SELECT TOP 30 AVG(Total_MB - (East_MB + West_MB)) AS Other,
                    AVG(East_MB) AS East,
                    AVG(West_MB) AS West
                    FROM [dbo].[Stats]
                    WHERE Rack_Code = 'ABC'

并提供错误的输出

enter image description here

请告知

1 个答案:

答案 0 :(得分:6)

你几乎拥有它,你所要做的就是将你的TOP 30置于子查询或CTE内而不是你的AVG

SELECT AVG(Total_MB - ( East_MB + West_MB )) AS Other
   ,AVG(East_MB) AS East
   ,AVG(West_MB) AS West
FROM (
       SELECT TOP 30 *
        FROM [dbo].[stats]
        WHERE Rack_Code = 'ABC'
        ORDER BY Date_of_Record DESC
     ) a

请注意,在子查询中唯一可以使用ORDER BY的是TOP条款。

CTE解决方案,

;WITH   base
          AS (
               SELECT TOP 30 *
                FROM [dbo].[stats]
                WHERE Rack_Code = 'ABC'
                ORDER BY Date_of_Record DESC
             )
    SELECT AVG(Total_MB - ( East_MB + West_MB )) AS Other
           ,AVG(East_MB) AS East
           ,AVG(West_MB) AS West
        FROM base
关于CTE的

Documentataion。请注意,SQL-Server将CTE视为视图。这可能会引入一些开销,如果嵌套得足够深,那么查询优化器就无法读取统计信息,并且可能会造成很大的性能下降。