SQL AVG超过行的子集

时间:2014-10-28 15:44:12

标签: sql sql-server-2008 aggregate-functions

我遇到一个平均值的问题,我试图在频繁运行的查询中计算。这个小提琴应该显示我到目前为止所得到的:

http://sqlfiddle.com/#!3/6afa9/4

理想情况下,我想将平均计算限制为最近提交的4个报告。所以预期的结果应该是

+----+---------+
| id | runtime |
+----+---------+
|  1 |     600 |
|  2 |     660 |
+----+---------+

我试过OVER PARTITION但似乎找不到与我想要的东西接近的东西。

1 个答案:

答案 0 :(得分:2)

您可以在CTE中嵌入一个ROW_NUMBER(),以便在截止日期前获得最近的4次运行。

;WITH cte AS (
  SELECT
    id,
    DATEDIFF(minute, started, finished) AS runtime,
    ROW_NUMBER() OVER (PARTITION BY id ORDER BY finished DESC) AS RowNum
  FROM report
)
  SELECT
    id,
    AVG(runtime) AS AvgRuntime
  FROM cte
  WHERE RowNum <= 4
  GROUP BY id

产生这些结果

| ID | AVGRUNTIME |
|----|------------|
|  1 |        600 |
|  2 |        660 |

链接到SQL小提琴:http://sqlfiddle.com/#!3/6afa9/8/0