从内部查询中获取聚合值

时间:2016-04-13 10:49:17

标签: sql sql-server

这很好用:

SELECT TOP 100 ExecutionTime 
FROM [Brokermate_CONFIG].[dbo].[QueryLog] 
ORDER BY ExecutedOn DESC

但是试图获得平均值会给我一个错误

SELECT AVG(executiontime) 
FROM
    (SELECT TOP 100 ExecutionTime 
     FROM [Brokermate_CONFIG].[dbo].[QueryLog] 
     ORDER BY ExecutedOn DESC
    )

错误:

  

')附近的语法错误。

正确的语法是什么?

由于

2 个答案:

答案 0 :(得分:4)

您错过了alias子查询的名称

尝试下面

SELECT AVG(executiontime) 
FROM
 (SELECT TOP 100 ExecutionTime 
  FROM [Brokermate_CONFIG].[dbo].[QueryLog]   
  ORDER BY ExecutedOn DESC
 ) A -- You need to have alias name here

答案 1 :(得分:3)

为子查询添加别名:

SELECT AVG(sub.executiontime) AS average_execution_time
FROM (SELECT TOP 100 ExecutionTime 
      FROM [Brokermate_CONFIG].[dbo].[QueryLog] 
      ORDER BY ExecutedOn DESC) AS sub