douquan3294 2018-07-20 16:01
浏览 79
已采纳

按日期时间的MYSQL / PHP加权平均值

Hi I have a DB with following data:

Table: "history_data"

VALUE , DATE
100   , 2010-10-01 00:00:00
105   , 2010-10-01 00:00:05
106   , 2010-10-01 00:00:08
103   , 2010-10-01 00:00:10

If I do a simple AVG with MYSQL ( SELECT AVG('VALUE') AS CURRENT_AVG FROM "history_data") it results "103.5" that it's wrong because I need a weighted average based on datetime (from 2010-10-01 00:00:05 to 2010-10-01 00:00:07 the value still equal to 105)

The right operation to do this in math is:

$values = [100,100,100,100,105,105,105,106,106,103];

echo array_sum($values) / count($values);

results: 103 that is right....

I have created two array one with Value and Date index, another only with dateinterval in php. Than I merge it and after process it... but it's to resources expensive.... ( in production I need to make an weighted average of 12 hours. 43 200 seconds...)

Where is the most efficiently method to do this?

  • 写回答

3条回答 默认 最新

  • doutuo7609 2018-07-20 20:51
    关注

    At least the most efficient method is do it in PHP

        $current_avg = $current_avg->fetchAll(PDO::FETCH_ASSOC);
        $last_util_value = "";
        $last_util_date = "";
        $final_avg_array = array();
        foreach ($current_avg as $key => $value) {
            if(empty($last_util_value)){
                $last_util_value = $value["val_ask"];
                $last_util_date = strtotime($value["Date"]);
                $second_time = $last_util_date - $past_time_second;
            }else{
                $second_time = strtotime($value["Date"]) - $last_util_date;
            }
    
            if($second_time > 0){
                for ($i = 1; $i <= $second_time; $i++) {
                    array_push($final_avg_array,$value["val_ask"]);
                }
            }
            $last_util_value = $value["val_ask"];
            $last_util_date = strtotime($value["Date"]);
        }
       }
      //6366.26937251
      $avg = array_sum($final_avg_array) / count($final_avg_array);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器