开发者

Howto query average of most recent data in sqlserver

开发者 https://www.devze.com 2023-01-20 02:54 出处:网络
I want to find the average of the most recent x results. Is it possible to use an aggregate function on a limited number of results with sql server?

I want to find the average of the most recent x results. Is it possible to use an aggregate function on a limited number of results with sql server?

Here is what I have tried and the errors I get:

select avg(top(100) convert(float, AnalysisData))
from tab
order by DateP开发者_StackOverflowerformed desc

Msg 156, Level 15, State 1, Line 1 Incorrect syntax near the keyword 'top'.

select AVG(data)
from (
select top(100) convert(float, AnalysisData) As data
from tab
order by DatePerformed desc
);

Msg 102, Level 15, State 1, Line 7 Incorrect syntax near ')'.

This is sql server 2008


In your second example, you need an alias name for the subquery:

select AVG(data)
from (
    select top 100 convert(float, AnalysisData) As data
    from tab
    order by DatePerformed desc
) Top100Records;

You probably don't need the parenthesis around 100 either.

0

精彩评论

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