【问题标题】:current average for each row of data每行数据的当前平均值
【发布时间】:2015-07-12 17:13:11
【问题描述】:

我有一个带有 as-

日期的表格输出   输出
1-1 月 20 日
40 年 1 月 2 日
3-1 月 30 日
1 月 4 日  100
120 年 1 月 5 日
10 年 1 月 6 日
90 年 1 月 7 日
80 年 1 月 8 日
9 月 60 日

直到

120 年 12 月 31 日

我需要查询每个日期的平均值,其中平均值是从第一个日期到当前日期的值的累积平均值,如下所示 -
日期   输出  平均
1-1 月 20 日 20 日
1 月 2 日 40 30
1 月 3 日  30   30
1 月 4 日 100 47.5
1 月 5 日 120 62
10 年 1 月 6 日 53.5


有人可以帮忙吗?

【问题讨论】:

标签: mysql average


【解决方案1】:
SELECT `date`, `output`, 
(SELECT avg(`output`) from Table1 where Table1.`date` <= b.`date`) 
as `average` FROM Table1 b

sqlfiddle here

【讨论】:

    【解决方案2】:

    Axel 的答案有效,或者,您可以在单个查询中使用变量:

    set @count := 0;
    set @total := 0;
    select case when ((@count := @count + 1) and ((@total := @total + output) or 1))
                  then @total / @count
            end rolling_average,
            `date`, 
            `output`
      from data
      order by `date` asc
    

    http://sqlfiddle.com/#!9/2e006/14

    这避免了依赖子查询,这取决于数据的大小可能会带来更好的性能。

    【讨论】:

    • 如果没有 order by 子句,则不应依赖此解决方案。
    • 正如在别处指出的那样——如果第一个值为 0,它也会失败——现在不会了。 null 的可能性可能是也可能不是问题,取决于数据集。我没关系
    【解决方案3】:

    Pala 的想法是个好主意。除了缺少order by 之外,如果累积总和为零或output 哪里曾经NULL,它也会失败。这很容易解决:

    select `date`, `output`,
           if((@count := @count + 1) is not null,
              if((@total := @total + coalesce(output, 0)) is not null,
                 @total/@count, 0
                ), 0
              ) as running_average
    from data cross join
         (select @count := 0, @total := 0) init
    order by date;
    

    【讨论】:

      【解决方案4】:

      这是另一种方式,虽然 Pala 的方法可扩展性更好...

      SELECT x.*
           , AVG(y.output) avg 
        FROM output x 
        JOIN output y 
          ON y.date <= x.date 
       GROUP 
          BY x.date 
       ORDER 
          BY x.date;
      

      order by 子句在 5.5/5.6 版本之后显然是必要的

      【讨论】:

        猜你喜欢
        • 2015-03-12
        • 1970-01-01
        • 2017-11-12
        • 2021-01-11
        • 1970-01-01
        • 2015-05-11
        • 2016-05-26
        • 2017-09-21
        • 2015-08-02
        相关资源
        最近更新 更多