简体   繁体   中英

How to get the average price for the X most recent rows based on date?

I am looking to calculate moving averages over variable dates.

My database is structured:

id int    
date date
price decimal

For example, I'd like to find out if the average price going back 19 days ever gets greater than the average price going back 40 days within the past 5 days. Each of those time periods is variable.

What I am getting stuck on is selecting a specific number of rows for subquery.

Select * from table
order by date
LIMIT 0 , 19

Knowing that there will only be 1 input per day, can I use the above as a subquery? After that the problem seems trivial....

if you only have one input per day you don't need id, date can be your primary id? Am i missing something? Then use select sum

SELECT SUM(price) AS totalPrice FROM table Order by date desc Limit (most recent date),(furthest back date) 

totalPrice/(total days) 

I may not understand your question

Yes you can use that as a sub-query like this:

SELECT 
    AVG(price) 
FROM 
    (SELECT * FROM t ORDER BY date DESC LIMIT 10) AS t1;

This calculates the average price for the latest 10 rows.

see fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM