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 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程