【问题标题】:How to get the average price for the X most recent rows based on date?如何根据日期获取最近 X 行的平均价格?
【发布时间】:2013-04-27 00:00:30
【问题描述】:

我希望计算可变日期的移动平均值。

我的数据库是结构化的:

id int    
date date
price decimal

例如,我想知道过去 5 天内过去 19 天的平均价格是否高于过去 40 天的平均价格。每个时间段都是可变的。

我遇到的问题是为子查询选择特定数量的行。

Select * from table
order by date
LIMIT 0 , 19

知道每天只有 1 个输入,我可以将上面的内容用作子查询吗?之后问题似乎微不足道....

【问题讨论】:

  • 你可能想使用order by date DESC

标签: mysql sql sql-order-by average


【解决方案1】:

如果您每天只有一个输入,您不需要 id,日期可以是您的主要 id?我错过了什么吗?然后使用选择总和

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

totalPrice/(total days) 

我可能不明白你的问题

【讨论】:

    【解决方案2】:

    是的,您可以像这样将其用作子查询:

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

    这会计算最近 10 行的平均价格。

    see fiddle.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-25
      • 1970-01-01
      • 2017-04-14
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      相关资源
      最近更新 更多