简体   繁体   English

根据值的差异计算每天的平均值

[英]Calculate average per day based on the difference of the values

I have a table:我有一张桌子:

value价值 updated_at更新时间 ID ID
5 5 2022-1-1 12:00:00 2022-1-1 12:00:00 1 1
10 10 2022-1-1 12:00:30 2022-1-1 12:00:30 2 2
20 20 2022-1-1 12:02:30 2022-1-1 12:02:30 3 3

What I want to do is to get an average based on the updated_at column difference, and the values of course.我想要做的是根据updated_at列的差异以及当然的值来获得平均值。

So, I guess the formula should be:所以,我想公式应该是:

(sumof((value2 - value1) * (date2 - date1))) / (dateLast - dateFirst) where 1 and 2 means for each two rows when we traverse from the first to the last item. (sumof((value2 - value1) * (date2 - date1))) / (dateLast - dateFirst)当我们从第一个项目遍历到最后一个项目时,其中 1 和 2 表示每两行。 eg for this table we'll have:例如,对于这张桌子,我们将拥有:

First and second row: (value2 - value1) * (date2 - date1) = (10 - 5) * (30 (seconds)) = 150第一行和第二行: (value2 - value1) * (date2 - date1) = (10 - 5) * (30 (seconds)) = 150

for second and third row: (20 - 10) * 120 = 1200第二行和第三行: (20 - 10) * 120 = 1200

So the result is:所以结果是:

(1200 + 150) / (2022-1-1 12:02:30 - 2022-1-1 12:00:00) = 9

I probably can get this working with a self JOIN on ID and ID + 1 and I also can do the diff of last and first date, but I can't do them both in the same query, I have no idea how to do that?我可能可以使用 ID 和 ID + 1 上的自我 JOIN 来完成这项工作,我也可以计算最后一个日期和第一个日期的差异,但我不能在同一个查询中同时执行它们,我不知道该怎么做? is this even possible to be done in a single query?这甚至可以在单个查询中完成吗?


Update更新

My MySql version is 5.6我的 MySql 版本是 5.6

For MySql 8.0+ you can use LAG() window function to get each row's previous values and then aggregate:对于 MySql 8.0+,您可以使用LAG() window function 获取每一行的先前值,然后聚合:

WITH cte AS (
  SELECT *,
         value - LAG(value) OVER (ORDER BY updated_at) dif_value,
         UNIX_TIMESTAMP(updated_at) - UNIX_TIMESTAMP(LAG(updated_at) OVER (ORDER BY updated_at)) dif_time
  FROM tablename
)
SELECT SUM(dif_value * dif_time) / 
       (UNIX_TIMESTAMP(MAX(updated_at)) - UNIX_TIMESTAMP(MIN(updated_at))) result 
FROM cte;

For previous versions and if there are no gaps between the ids, use a self join:对于以前的版本,如果 id 之间没有间隙,请使用自联接:

SELECT SUM(dif_value * dif_time) / 
       (UNIX_TIMESTAMP(MAX(updated_at)) - UNIX_TIMESTAMP(MIN(updated_at))) result 
FROM (
  SELECT t1.*,
         t1.value - t2.value dif_value,
         UNIX_TIMESTAMP(t1.updated_at) - UNIX_TIMESTAMP(t2.updated_at) dif_time
  FROM tablename t1 LEFT JOIN tablename t2
  ON t1.ID = t2.ID + 1
) t; 

See the demo .请参阅演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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