开发者

How to get the average of the last X values?

If I have a table with two columns - value and time_stamp - how can I use SQL to get the average of the last X values?

One statement or several, it doesn't matter.

Maybe something like SELECT value FROM table ORDER BY time_stamp DESC LIMIT x ? Then in my program, I could get each value, total them and average them? That's my best guess so far as I am a SQL beginner.

I am aware that SQL can total / average, but I am unsure how to combine that with a request to apply it to the latest X values...


Note to anyone else seeking to do this: in addition to the accepted answer for the last X values, I also found by googling that it is easy to do for a time period, such as a minute or hour, by using someth开发者_JS百科ing like SELECT AVG(somefield) FROM sometable WHERE datefield BETWEEN '2003-08-10' AND '2003-08-26'.


You use the AVG() aggregate on the result of a subselect which does the initial LIMIT. Just be sure to substitute the correct LIMIT value for n on the inner query.

SELECT AVG(a.value) AS the_average
FROM (SELECT value FROM tbl ORDER BY time_stamp DESC LIMIT n) a;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜